浏览器端js写csv文件

假设使用rest方式取到的数据为json格式。代码原路径:https://gist.github.com/Sikwan/4326948

function Json2CSV(objArray){
  var 
    getKeys = function(obj){
      var keys = [];
      for(var key in obj){
        keys.push(key);
      }
      return keys.join();
    }, objArray = format_json(objArray)
    , array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray
    , str = ''
  ;


  for (var i = 0; i < array.length; i++) {
    var line = '';
    for (var index in array[i]) {
      if(line != '') line += ','
   
      line += array[i][index];
    }


    str += line + '\r\n';
  }


  str = getKeys(objArray[0]) + '\r\n' + str;


  var a = document.createElement('a');
  var blob = new Blob([str], {'type':'application\/octet-stream'});
  a.href = window.URL.createObjectURL(blob);
  a.download = 'export.csv';
  a.click();
  return true;
}


写好的csv文件,用excel打开后会有中文乱码问题,解决办法,加入BOM头

将代码中这句

var blob = new Blob([str], {'type':'application\/octet-stream'});
改为
var blob = new Blob(['\uFEFF' + str], {'type':'application\/octet-stream'});


你可能感兴趣的:(js,乱码,csv)