Export xlsx to csv in Angular

╄→гoц情女王★ 提交于 2021-02-11 13:25:08

问题


I am using XLSX to parse data from an xlsx file. The problem is that when I try to get the data, the data is different depending on whether I read it in XLSX and CSV.

I prefer to read it in CSV, since if I don't have to transform the dates according to the Excel format.

I am trying to convert the XLSX file to CSV when the user uploads the file. The way I try is:

const reader: FileReader = new FileReader();

reader.onload = (e: any) => {

    var binaryData = e.target.result;
    //Converting Binary Data to base 64
    var base64String = window.btoa(binaryData);

    const wb = XLSX.read(base64String, { type: 'base64' });
    const newFile = XLSX.write(wb, { bookType: 'csv', type: 'binary' });
    resolve(newFile);
}

reader.onerror = (error: any) => {
    reject(error);
}

reader.readAsBinaryString(file);

I'm using it on a promise. When promise is resolved, I parse it to XLSX.WorkSheet as follows:

const bstr: string = str;
const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary', raw: false });

const wsname: string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];

let options = { header: 1, raw: false };

let data = <any[][]>(XLSX.utils.sheet_to_json(ws, options));

return data;

The problem is that it is as if I had not done anything, since the data is still bad.

However, if I open Excel, and click on save as > CSV, read the data without problems. What am I doing wrong?

I'm using Angular 7.

来源:https://stackoverflow.com/questions/59827076/export-xlsx-to-csv-in-angular

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