node.js 在 Node 中的服务器上将 XLS 转换为 CSV

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34342425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:39:48  来源:igfitidea点击:

Convert XLS to CSV on the server in Node

node.jsexcelcsvnpmxls

提问by fnsjdnfksjdb

I have a client-side web application, with a very minimal node server to access some data that the client can't. One of these things is excel spreadsheets with .xls extensions.

我有一个客户端 Web 应用程序,它有一个非常小的节点服务器来访问客户端无法访问的一些数据。其中之一是带有 .xls 扩展名的 Excel 电子表格。

I'm trying to get my server set up to download the xls, convert it to csv, and then send it back to the client. I've got the download part done, and I'm sure I can figure out the "send back" part, but I can't for the life of me find a good library to convert from xls to csv.

我正在尝试设置我的服务器以下载 xls,将其转换为 csv,然后将其发送回客户端。我已经完成了下载部分,我确定我可以弄清楚“发回”部分,但是我一生都找不到一个好的库来从 xls 转换为 csv。

Can someone point me to a library that can do that in a simple fashion? The excel file is just one sheet, no complicated workbooks or anything.

有人可以给我指出一个可以以简单方式做到这一点的图书馆吗?excel 文件只是一张纸,没有复杂的工作簿或任何东西。

Or is there another way of doing this I'm not thinking of?

或者有没有我没有想到的另一种方法?

回答by heinst

There is no library that I am aware of, but you could use node-xlsxto parse the excel file, get the rows and make the CSV yourself. Here's an example:

没有我知道的库,但您可以使用node-xlsx来解析 excel 文件,获取行并自己制作 CSV。下面是一个例子:

var xlsx = require('node-xlsx');
var fs = require('fs');
var obj = xlsx.parse(__dirname + '/test.xls'); // parses a file
var rows = [];
var writeStr = "";

//looping through all sheets
for(var i = 0; i < obj.length; i++)
{
    var sheet = obj[i];
    //loop through all rows in the sheet
    for(var j = 0; j < sheet['data'].length; j++)
    {
            //add the row to the rows array
            rows.push(sheet['data'][j]);
    }
}

//creates the csv string to write it to a file
for(var i = 0; i < rows.length; i++)
{
    writeStr += rows[i].join(",") + "\n";
}

//writes to a file, but you will presumably send the csv as a      
//response instead
fs.writeFile(__dirname + "/test.csv", writeStr, function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("test.csv was saved in the current directory!");
});

回答by Cassio

I am using this package to convert XLSX to CSV: https://www.npmjs.com/package/xlsx

我正在使用此包将 XLSX 转换为 CSV:https: //www.npmjs.com/package/xlsx

XLSX = require('xlsx');

const workBook = XLSX.readFile(inputFilename);
XLSX.writeFile(workBook, outputFilename, { bookType: "csv" });