如何将XLSX添加到服务器端Node JS

时间:2019-08-14 12:09:27

标签: node.js excel xlsx

我希望它读取服务器端的 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'”

2 个答案:

答案 0 :(得分:0)

要安装它:

npm i xlsx

要使用它:

const XLSX = require("xlsx");

let workbook = XLSX.readFile("./test.xlsx");

console.log(workbook);

(您可以在此处使用var代替const和let)

答案 1 :(得分:0)

您可以为此使用 xlsx npm 包。

npm install 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' },   
 ]