【问题标题】:How to Add XLSX to server side Node JS如何将 XLSX 添加到服务器端 Node JS
【发布时间】:2019-08-14 12:09:27
【问题描述】:

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

【问题讨论】:

标签: node.js excel xlsx


【解决方案1】:

要安装它:

npm i xlsx

使用它:

const XLSX = require("xlsx");

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

console.log(workbook);

(这里可以用 var 代替 const 和 let)

【讨论】:

    【解决方案2】:

    您可以为此使用 xlsx npm 包。

    npm install xlsx
    https://www.npmjs.com/package/xlsx

    这是我使用节点 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' },   
     ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      • 2019-05-24
      • 2020-08-10
      • 2021-05-01
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      相关资源
      最近更新 更多