How to export JavaScript array info to csv (on client side)?

前端 未结 29 1672
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 21:55

I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8 and have all the attribute info in array, which loo

29条回答
  •  甜味超标
    2020-11-21 22:32

    People are trying to create their own csv string, which fail on edge cases, e.g. special characters, surely this is a solved problem right?

    papaparse - use for JSON to CSV encoding. Papa.unparse().

    import Papa from "papaparse";
    
    const downloadCSV = (args) => {  
    
      let filename = args.filename || 'export.csv';
      let columns = args.columns || null;
    
      let csv = Papa.unparse({ data: args.data, fields: columns})
      if (csv == null) return;
    
      var blob = new Blob([csv]);
      if (window.navigator.msSaveOrOpenBlob)  // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
          window.navigator.msSaveBlob(blob, args.filename);
      else
      {
          var a = window.document.createElement("a");
          a.href = window.URL.createObjectURL(blob, {type: "text/plain"});
          a.download = filename;
          document.body.appendChild(a);
          a.click();  // IE: "Access is denied"; see: https://connect.microsoft.com/IE/feedback/details/797361/ie-10-treats-blob-url-as-cross-origin-and-denies-access
          document.body.removeChild(a);
      }
    
    }
    

    Example usage

    downloadCSV({ 
      filename: 'filename.csv',
      data: [{'a': '1', 'b': 2'}],
      columns: ['a','b']
    });
    

    https://github.com/mholt/PapaParse/issues/175 - See this comment for browser support discussion.

提交回复
热议问题