Javascript to csv export encoding issue

前端 未结 8 1363
Happy的楠姐
Happy的楠姐 2020-11-29 00:33

I need to export javascript array to excel file and download it I\'m doing it in this code. data is a javascript object array.

var csvContent = \"data:t         


        
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 01:13

    Option 1

    use iconv-lite library and encode your output to ascii before send it back to the user. Example:

    var iconv = require('iconv-lite');
    buf = iconv.encode(str, 'win1255'); // return buffer with windows-1255 encoding
    

    Option 2

    Write on the head of the file the BOM header of UTF-8 encoding. Example:

    res.header('Content-type', 'text/csv; charset=utf-8');
    res.header('Content-disposition', 'attachment; filename=excel.csv'); 
    res.write(Buffer.from('EFBBBF', 'hex')); // BOM header
    
    // rest of your code
    

    Option 3

    Use base64 url format like data:text/csv;base64,77u/Zm9vLGJhcg0KYWFhLGJiYg==. This method will work on client-side also (IE10+, FF, Chrome, Opera, Safari).

    For example:

    window.location = "data:text/csv;base64,77u/" + btoa("foo,bar\r\naaa,bbb");
    

提交回复
热议问题