Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTF-8 encoidng issue when exporting csv file , JavaScript

I use the below function to export an array to a csv files in JavaScript, but the Chinese characters become messy code with Microsoft Excel 2013 in Windows7.

I open the exported file with a notepad but it displays finely.

function arrayToCSVConvertor(arrData, reportTitle) {     var CSV='';     arrData.forEach(function(infoArray, index){         var dataString = infoArray.join(",");         dataString= dataString.split('\n').join(';');         CSV += dataString+ "\n";     });      if (CSV == '') {         alert("Invalid data");         return;     }      //create a link and click, remove     var link = document.createElement("a");     link.id="lnkDwnldLnk";      //this part will append the anchor tag and remove it after automatic click     document.body.appendChild(link);      var csv = CSV;      var blob = new Blob([csv], { type: ' type: "text/csv;charset=UTF-8"' });//Here, I also tried charset=GBK , and it does not work either     var csvUrl = createObjectURL(blob);      var filename = reportTitle+'.csv';      if(navigator.msSaveBlob){//IE 10         return navigator.msSaveBlob(blob, filename);     }else{         $("#lnkDwnldLnk")             .attr({                 'download': filename,                 'href': csvUrl             });         $('#lnkDwnldLnk')[0].click();         document.body.removeChild(link);     } } 
like image 426
JaskeyLam Avatar asked Aug 12 '15 08:08

JaskeyLam


People also ask

Are CSV files UTF-8?

Google Spreadsheet correctly exports UTF-8 encoded CSV files by default. From the File menu, choose Download As and select Comma-separated values. The downloaded file will be UTF-8 encoded.

Is CSV Ascii or UTF-8?

CSV UTF-8 (comma delimited). It is Unicode Transformation Format 8-bit encoding that supports many special characters, including hieroglyphs and accented characters, and is backward compatible with ASCII.


2 Answers

Problem solved by adding BOM at the start of the csv string:

var csv = "\ufeff"+CSV; 
like image 142
JaskeyLam Avatar answered Sep 23 '22 18:09

JaskeyLam


This is my solution:

var blob = new Blob(["\uFEFF"+csv], {     type: 'text/csv; charset=utf-18' }); 
like image 45
Santy SC Avatar answered Sep 24 '22 18:09

Santy SC