change XLSX column datatype to number in Angular 5

孤街醉人 提交于 2020-06-28 11:05:21

问题


  1. i am using xlsx library for export to excel ("xlsx": "0.16.1")
  2. i have three columns with thousand separator number, so when i export that data then it will consider as a string, but i want number type, here is code of Export to Excel file

    public downloadExcel(json: any[], excelFileName: string, merges?: any): void {
        let worksheet: XLSX.WorkSheet;
        if (merges) {
            worksheet = XLSX.utils.aoa_to_sheet(json);
            worksheet['!merges'] = merges;
        } else {
            worksheet = XLSX.utils.json_to_sheet(json);
        }
    
        const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    
        var fmt = '0'; 
        workbook.Sheets['data']['C2'].z = fmt;
    
        const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
        this.saveAsExcelFile(excelBuffer, excelFileName);
    }
    
    private saveAsExcelFile(buffer: any, fileName: string): void {
        const data: Blob = new Blob([buffer], {
            type: 'application/octet-stream'
        });
        FileSaver.saveAs(data, fileName + "_" + new Date().toLocaleDateString() + "_" + new Date().toLocaleTimeString() + EXCEL_EXTENSION);
    }
    

so i want to change C,D,E,F column data type, so i can directly SUM that column,


回答1:


Before generating Excel from JSON, modify JSON by removing Comma(,) from numbers and convert them into numbers like:

parseInt('10,340'.replace(/,/g, ''))

This way you will store the number without comma so Excel will consider that column as a number automatically.

Let me know if you have any questions.

------------EDIT------------

You can replace the comma(,) from the original number as shown above and use column formatting #,##0.00. This way it will display comma at every thousand points but actually it will store it as a number so you can do all arithmetic operations



来源:https://stackoverflow.com/questions/62154444/change-xlsx-column-datatype-to-number-in-angular-5

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