Convert XLS to CSV on the server in Node

强颜欢笑 提交于 2019-12-18 11:54:04

问题


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.

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.

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.

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


回答1:


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

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!");
});



回答2:


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

XLSX = require('xlsx');

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


来源:https://stackoverflow.com/questions/34342425/convert-xls-to-csv-on-the-server-in-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!