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
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
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