Home:ALL Converter>How to upload and read excel file in nodejs?

How to upload and read excel file in nodejs?

Ask Time:2022-01-03T14:44:51         Author:Sundar Gautam

Json Formatter

I want to build an API "/upload/excel" that will allow users to import an excel file and inside it after receiving an excel file, it will read its field and save it into database.

How to achieve this?

Author:Sundar Gautam,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/70562438/how-to-upload-and-read-excel-file-in-nodejs
abderrezague mohamed :

I am using multer for uploading the file and xlsx to process it and mongodb as a database (mongoose for the model):\nLead is the data model, you have to add the Excel sheet columns name. See mongoose documentation for more information\nconst express = require("express");\nconst multer = require("multer");\nconst connectDB = require("./config/db");\nconst Lead = require("./models/Lead");\n\nconnectDB();\n\nconst uploadXLSX = async (req, res, next) => {\n try {\n let path = req.file.path;\n var workbook = XLSX.readFile(path);\n var sheet_name_list = workbook.SheetNames;\n let jsonData = XLSX.utils.sheet_to_json(\n workbook.Sheets[sheet_name_list[0]]\n );\n if (jsonData.length === 0) {\n return res.status(400).json({\n success: false,\n message: "xml sheet has no data",\n });\n }\n let savedData = await Lead.create(jsonData);\n\n return res.status(201).json({\n success: true,\n message: savedData.length + " rows added to the database",\n });\n } catch (err) {\n return res.status(500).json({ success: false, message: err.message });\n }\n};\n\nvar storage = multer.diskStorage({\n destination: function (req, file, cb) {\n cb(null, "uploads");\n },\n filename: function (req, file, cb) {\n cb(null, Date.now() + "-" + file.originalname);\n },\n});\n\nconst upload = multer({ storage: storage });\n\napp.post("/upload", upload.single("xlsx"), uploadXLSX);\n\nconst port = process.env.PORT || 5000;\n\nconst server = app.listen(port, () => {\n console.log("app running on port", port);\n});\n\nSo from here when you make a call to localhost:5000/upload with postman see picture below\n",
2022-06-02T15:33:19
yy