Ads

NextJs - Read Excel file and pass to the GET end point.

Hello in this article you will learn how to read the excel file from NextJS and pass to the GET End point



1. Create New NextJS Application

    create-next-app sample-excel-read

2. Install Excel dependency

     npm install xlsx

3. Create the excel file with extension .xlsx and place that into public folder


 Also have added the below mentioned data to excel file


4. Create the folder called utilities under app folder and create filename called excelReader.js

    Paste or Write the below code inside excelReader.js

import fs from "fs";
import * as XLSX from "xlsx";
import path from "path";

const readExcelFile = (fileName) => {
    console.log(fileName)
  const filePath = path.join(process.cwd(), "public", fileName);

  const fileContent = fs.readFileSync(filePath);
  const workbook = XLSX.read(fileContent, { type: "buffer" });
  const sheetName = workbook.SheetNames[0];
  const sheet = workbook.Sheets[sheetName];
  const data = XLSX.utils.sheet_to_json(sheet, { header: 1 });

  return data;
};

export default readExcelFile;

5. Next Create End Point for Get, to fetch the excel data.

    Create the folder called api inside app folder and the folder called user

    Next Create file called route.js

    


        Then add the below code to route.js file

import readExcelFile from "@/app/uitilities/excelReader";

const fileName = "SampleData.xlsx";

export const GET = async (request) => {
  const data = readExcelFile(fileName);
  return new Response(JSON.stringify(data), { status: "200" });
};

6. Its time to run the application

    Just run the below command in VS Code Terminal --> New Terminal

    npm run


Then go to browser and hit the URL

http://localhost:3000/api/users

Note: Port might be different for you, please check the command line for valid port. In my case it is 3000 hence using it, Please find the output below




Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !