我知道有很多这种性质的问题,但我需要使用JavaScript来做到这一点。我使用Dojo 1.8并在数组中拥有所有属性信息,它看起来像这样:

[["name1", "city_name1", ...]["name2", "city_name2", ...]]

知道我如何在客户端将此导出为CSV吗?


当前回答

我使用这个函数将字符串[][]转换为csv文件。如果单元格包含",a或其他空格(空格除外),则引用该单元格:

/**
 * Takes an array of arrays and returns a `,` sparated csv file.
 * @param {string[][]} table
 * @returns {string}
 */
function toCSV(table) {
    return table
        .map(function(row) {
            return row
                .map(function(cell) {
                    // We remove blanks and check if the column contains
                    // other whitespace,`,` or `"`.
                    // In that case, we need to quote the column.
                    if (cell.replace(/ /g, '').match(/[\s,"]/)) {
                        return '"' + cell.replace(/"/g, '""') + '"';
                    }
                    return cell;
                })
                .join(',');
        })
        .join('\n'); // or '\r\n' for windows

}

注意:不工作在Internet Explorer < 11除非地图是填充。

注意:如果单元格包含数字,你可以在If (cell.replace…将数字转换为字符串。

或者你可以用ES6在一行中写:

t.map(r=>r.map(c=>c.replace(/ /g, '').match(/[\s,"]/)?'"'+c.replace(/"/g,'""')+'"':c).join(',')).join('\n')

其他回答

ES6的一个箭头函数:

const dataToCsvURI = (data) => encodeURI(
`data:text/csv;charset=utf-8,${data.map((row, index) =>  row.join(',')).join(`\n`)}`
);

然后:

window.open(
  dataToCsvURI(
   [["name1", "city_name1"/*, ...*/], ["name2", "city_name2"/*, ...*/]]
  )
);

如果有人在reactjs中需要这个,react-csv就在那里

基于上面的答案,我创建了这个函数,并在IE 11、Chrome 36和Firefox 29上进行了测试

function exportToCsv(filename, rows) {
    var processRow = function (row) {
        var finalVal = '';
        for (var j = 0; j < row.length; j++) {
            var innerValue = row[j] === null ? '' : row[j].toString();
            if (row[j] instanceof Date) {
                innerValue = row[j].toLocaleString();
            };
            var result = innerValue.replace(/"/g, '""');
            if (result.search(/("|,|\n)/g) >= 0)
                result = '"' + result + '"';
            if (j > 0)
                finalVal += ',';
            finalVal += result;
        }
        return finalVal + '\n';
    };

    var csvFile = '';
    for (var i = 0; i < rows.length; i++) {
        csvFile += processRow(rows[i]);
    }

    var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, filename);
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}

例如: https://jsfiddle.net/jossef/m3rrLzk0/

人们尝试创建自己的csv字符串,在边缘情况下失败,例如特殊字符,这肯定是一个解决的问题,对吧?

papaparse -用于JSON到CSV编码。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);
  }

}

示例使用

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

https://github.com/mholt/PapaParse/issues/175 -请参阅此评论了解浏览器支持讨论。

在Chrome 35更新中,下载属性行为发生改变。

https://code.google.com/p/chromium/issues/detail?id=373182

要在chrome中工作,使用这个

var pom = document.createElement('a');
var csvContent=csv; //here we load our csv data 
var blob = new Blob([csvContent],{type: 'text/csv;charset=utf-8;'});
var url = URL.createObjectURL(blob);
pom.href = url;
pom.setAttribute('download', 'foo.csv');
pom.click();

这个解决方案应该适用于Internet Explorer 10+, Edge,新旧版本的Chrome, FireFox, Safari, ++

已接受的答案不能在IE和Safari中使用。

// Example data given in question text var data = [ ['name1', 'city1', 'some other info'], ['name2', 'city2', 'more info'] ]; // Building the CSV from the Data two-dimensional array // Each column is separated by ";" and new line "\n" for next row var csvContent = ''; data.forEach(function(infoArray, index) { dataString = infoArray.join(';'); csvContent += index < data.length ? dataString + '\n' : dataString; }); // The download function takes a CSV string, the filename and mimeType as parameters // Scroll/look down at the bottom of this snippet to see how download is called var download = function(content, fileName, mimeType) { var a = document.createElement('a'); mimeType = mimeType || 'application/octet-stream'; if (navigator.msSaveBlob) { // IE10 navigator.msSaveBlob(new Blob([content], { type: mimeType }), fileName); } else if (URL && 'download' in a) { //html5 A[download] a.href = URL.createObjectURL(new Blob([content], { type: mimeType })); a.setAttribute('download', fileName); document.body.appendChild(a); a.click(); document.body.removeChild(a); } else { location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported } } download(csvContent, 'dowload.csv', 'text/csv;encoding:utf-8');

运行代码片段将下载csv格式的模拟数据

归功于dandavis https://stackoverflow.com/a/16377813/1350598