![](/img/trans.png)
[英]How to add a node js emit event in server side to emit new records inserted in database?
[英]How to Add XLSX to server side Node JS
我希望它在服務器端讀取XLSX Excel文件
我嘗試使用“node install xlsx”進行安裝
var XLSX = require('xlsx');
var XLSdata = null;
const fs = require('fs');
// First I want to read the file
//console.log("ovde", fs);
fs.readFile('/roster.xls', function (err, data) {
///console.log("dir", __dirname);
console.log("error", err);
//console.log("ovde",data);
XLSdata = data;
});
try {
var workbook = XLSX.read(XLSdata, {type: 'binary'});
}
catch(err) {
console.log("error",err.message);
return;
}
當我編譯代碼時出現錯誤:
“錯誤:找不到模塊‘xlsx’”
要安裝它:
npm i xlsx
要使用它:
const XLSX = require("xlsx");
let workbook = XLSX.readFile("./test.xlsx");
console.log(workbook);
(你可以在這里使用 var 而不是 const 和 let)
您可以為此使用 xlsx npm 包。
npm 安裝 xlsx
https://www.npmjs.com/package/xlsx
以下是我使用 node js 的一些示例代碼:
const xlsxController= {};
const XLSX = require('xlsx');
xlsxController.getXlxsData= async (req, res) => {
try {
var workbook = XLSX.readFile('fileName.xlsx');
// file should be placed in root directory of your project.
// in my case my file is placed in public folder so I am using 'public/fileName.xlsx'
var sheet_name_list = workbook.SheetNames;
let data = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
// sheet_name_list[0] is the number for the sheet from which you wants to read data, you can use file name instead of '0' in i.e sheet_name_list['sheetName']
return res.status(200).send({
message: 'Request Processed Successfully',
data: data,
});
} catch (error) {
console.log("error:", error);
return res.status(500).send({
message: 'Internal server error',
error: error
});
}
}
module.exports = xlsxController;
// Output in my case:
data: [
{ clubName: 'A.l.c.g.a. ', region: 'Aberdeenshire' },
{ clubName: 'Abbey Hill', region: 'Berks, Bucks & Oxon' },
{ clubName: 'Abbey Hotel Golf & C.c. ', region: 'Worcestershire' },
{ clubName: 'Abbey Moor' },
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.