如何将JavaScript数组信息导出到csv(在客户端)?

时间:2013-02-19 16:49:24

标签: javascript csv dojo export client-side

我知道有很多这方面的问题,但我需要使用JavaScript来做到这一点。我正在使用Dojo 1.8并在数组中包含所有属性信息,如下所示:

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

知道如何将其导出到客户端的CSV吗?

29 个答案:

答案 0 :(得分:710)

您可以在原生JavaScript中执行此操作。您必须将数据解析为正确的CSV格式(假设您正在使用数组数组,如问题中所述):

const rows = [
    ["name1", "city1", "some other info"],
    ["name2", "city2", "more info"]
];

let csvContent = "data:text/csv;charset=utf-8,";

rows.forEach(function(rowArray) {
    let row = rowArray.join(",");
    csvContent += row + "\r\n";
});

或更短的方式(使用arrow functions):

const rows = [
    ["name1", "city1", "some other info"],
    ["name2", "city2", "more info"]
];

let csvContent = "data:text/csv;charset=utf-8," 
    + rows.map(e => e.join(",")).join("\n");

然后您可以使用JavaScript的window.openencodeURI函数来下载CSV文件,如下所示:

var encodedUri = encodeURI(csvContent);
window.open(encodedUri);

编辑:

如果您想为文件指定一个特定名称,则必须采用不同的方式,因为不支持使用{{1}访问数据URI } 方法。为了实现这一目标,您可以创建隐藏的window.open DOM节点并按如下方式设置其<a>属性:

download

答案 1 :(得分:202)

基于上面的答案,我创建了这个我在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/

答案 2 :(得分:69)

此解决方案适用于 Internet Explorer 10 +,Edge,旧版和新版 Chrome,FireFox,Safari,++

接受的答案不适用于IE和Safari。

&#13;
&#13;
// 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');
&#13;
&#13;
&#13;

运行代码段会将模拟数据下载为csv

对dandavis的信任https://stackoverflow.com/a/16377813/1350598

答案 3 :(得分:34)

我来到这里寻找更多的RFC 4180合规性而我找不到实现,所以我根据自己的需要制作了一个(可能效率低下)。我以为我会和大家分享。

var content = [['1st title', '2nd title', '3rd title', 'another title'], ['a a a', 'bb\nb', 'cc,c', 'dd"d'], ['www', 'xxx', 'yyy', 'zzz']];

var finalVal = '';

for (var i = 0; i < content.length; i++) {
    var value = content[i];

    for (var j = 0; j < value.length; j++) {
        var innerValue =  value[j]===null?'':value[j].toString();
        var result = innerValue.replace(/"/g, '""');
        if (result.search(/("|,|\n)/g) >= 0)
            result = '"' + result + '"';
        if (j > 0)
            finalVal += ',';
        finalVal += result;
    }

    finalVal += '\n';
}

console.log(finalVal);

var download = document.getElementById('download');
download.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(finalVal));
download.setAttribute('download', 'test.csv');

希望这将有助于将来的某些人。这结合了CSV的编码以及下载文件的能力。在我jsfiddle的例子中。您可以下载该文件(假设是HTML 5浏览器)或在控制台中查看输出。

更新:

Chrome现在似乎无法命名该文件。我不确定发生了什么或如何修复它,但每当我使用此代码(包括jsfiddle)时,下载的文件现在都被命名为download.csv

答案 4 :(得分:31)

来自@Default的解决方案在Chrome上运行得很完美(非常感谢!)但我遇到了IE问题。

这是一个解决方案(适用于IE10):

var csvContent=data; //here we load our csv data 
var blob = new Blob([csvContent],{
    type: "text/csv;charset=utf-8;"
});

navigator.msSaveBlob(blob, "filename.csv")

答案 5 :(得分:15)

在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();

答案 6 :(得分:14)

Working for all languages

        function convertToCsv(fName, rows) {
        var csv = '';
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            for (var j = 0; j < row.length; j++) {
                var val = row[j] === null ? '' : row[j].toString();
                val = val.replace(/\t/gi, " ");
                if (j > 0)
                    csv += '\t';
                csv += val;
            }
            csv += '\n';
        }

        // for UTF-16
        var cCode, bArr = [];
        bArr.push(255, 254);
        for (var i = 0; i < csv.length; ++i) {
            cCode = csv.charCodeAt(i);
            bArr.push(cCode & 0xff);
            bArr.push(cCode / 256 >>> 0);
        }

        var blob = new Blob([new Uint8Array(bArr)], { type: 'text/csv;charset=UTF-16LE;' });
        if (navigator.msSaveBlob) {
            navigator.msSaveBlob(blob, fName);
        } else {
            var link = document.createElement("a");
            if (link.download !== undefined) {
                var url = window.URL.createObjectURL(blob);
                link.setAttribute("href", url);
                link.setAttribute("download", fName);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url);
            }
        }
    }



    convertToCsv('download.csv', [
        ['Order', 'Language'],
        ['1', 'English'],
        ['2', 'Español'],
        ['3', 'Français'],
        ['4', 'Português'],
        ['5', 'čeština'],
        ['6', 'Slovenščina'],
        ['7', 'Tiếng Việt'],
        ['8', 'Türkçe'],
        ['9', 'Norsk bokmål'],
        ['10', 'Ελληνικά'],
        ['11', 'беларускі'],
        ['12', 'русский'],
        ['13', 'Українська'],
        ['14', 'հայերեն'],
        ['15', 'עִברִית'],
        ['16', 'اردو'],
        ['17', 'नेपाली'],
        ['18', 'हिंदी'],
        ['19', 'ไทย'],
        ['20', 'ქართული'],
        ['21', '中国'],
        ['22', '한국어'],
        ['23', '日本語'],
    ])

答案 7 :(得分:7)

//It work in Chrome and IE ... I reviewed and readed a lot of answer. then i used it and tested in both ... 

var link = document.createElement("a");

if (link.download !== undefined) { // feature detection
    // Browsers that support HTML5 download attribute
    var blob = new Blob([CSV], { type: 'text/csv;charset=utf-8;' });
    var url = URL.createObjectURL(blob);            
    link.setAttribute("href", url);
    link.setAttribute("download", fileName);
    link.style = "visibility:hidden";
}

if (navigator.msSaveBlob) { // IE 10+
   link.addEventListener("click", function (event) {
     var blob = new Blob([CSV], {
       "type": "text/csv;charset=utf-8;"
     });
   navigator.msSaveBlob(blob, fileName);
  }, false);
}

document.body.appendChild(link);
link.click();
document.body.removeChild(link);

//Regards

答案 8 :(得分:5)

使用csv数据.ie var blob = new Blob([data], type:"text/csv");

创建一个blob

如果浏览器支持保存blob,if window.navigator.mSaveOrOpenBlob)===true,则使用以下内容保存csv数据:window.navigator.msSaveBlob(blob, 'filename.csv')

如果浏览器不支持保存和打开blob,请将csv数据保存为:

var downloadLink = document.createElement('<a></a>');
downloadLink.attr('href', window.URL.createObjectURL(blob));
downloadLink.attr('download', filename);
downloadLink.attr('target', '_blank');
document.body.append(downloadLink);

完整代码段:

var filename = 'data_'+(new Date()).getTime()+'.csv';
var charset = "utf-8";
var blob = new Blob([data], {
     type: "text/csv;charset="+ charset + ";"
});
if (window.navigator.msSaveOrOpenBlob) {
     window.navigator.msSaveBlob(blob, filename);
} else {
    var downloadLink = document.element('<a></a>');
    downloadLink.attr('href', window.URL.createObjectURL(blob));
    downloadLink.attr('download', filename);
    downloadLink.attr('target', '_blank');  
    document.body.append(downloadLink); 
    downloadLink[0].click(); 
}

答案 9 :(得分:5)

以下是本机js解决方案。

function export2csv() {
  let data = "";
  const tableData = [];
  const rows = [
    ['111', '222', '333'],
    ['aaa', 'bbb', 'ccc'],
    ['AAA', 'BBB', 'CCC']
  ];
  for (const row of rows) {
    const rowData = [];
    for (const column of row) {
      rowData.push(column);
    }
    tableData.push(rowData.join(","));
  }
  data += tableData.join("\n");
  const a = document.createElement("a");
  a.href = URL.createObjectURL(new Blob([data], { type: "text/csv" }));
  a.setAttribute("download", "data.csv");
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}
<button onclick="export2csv()">Export array to csv file</button>

答案 10 :(得分:4)

这里有两个问题:

  1. 如何将数组转换为csv字符串
  2. 如何将该字符串保存到文件
  3. 第一个问题的所有答案(Milimetric除外)在这里看起来像是一种矫枉过正。 Milimetric的那个不包括altrenative要求,例如带引号的周围字符串或转换对象数组。

    以下是我对此的看法:

    对于一个简单的csv,一个map()和一个join()就足够了:

        var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];
        var csv = test_array.map(function(d){
            return d.join();
        }).join('\n');
    
        /* Results in 
        name1,2,3
        name2,4,5
        name3,6,7
        name4,8,9
        name5,10,11
    

    此方法还允许您在内部联接中指定除逗号之外的列分隔符。例如标签:d.join('\t')

    另一方面,如果你想正确地做并将字符串括在引号&#34;&#34;中,那么你可以使用一些JSON魔法:

    var csv = test_array.map(function(d){
           return JSON.stringify(d);
        })
        .join('\n') 
        .replace(/(^\[)|(\]$)/mg, ''); // remove opening [ and closing ]
                                       // brackets from each line 
    
    /* would produce
    "name1",2,3
    "name2",4,5
    "name3",6,7
    "name4",8,9
    "name5",10,11
    

    如果您有以下对象数组:

    var data = [
      {"title": "Book title 1", "author": "Name1 Surname1"},
      {"title": "Book title 2", "author": "Name2 Surname2"},
      {"title": "Book title 3", "author": "Name3 Surname3"},
      {"title": "Book title 4", "author": "Name4 Surname4"}
    ];
    
    // use
    var csv = data.map(function(d){
            return JSON.stringify(Object.values(d));
        })
        .join('\n') 
        .replace(/(^\[)|(\]$)/mg, '');
    

答案 11 :(得分:4)

这里有很多自己动手的解决方案,用于将数据转换为CSV,但几乎所有这些解决方案在数据类型方面都有各种注意事项,它们可以正确地格式化而不会绊倒Excel等。

为什么不使用经证实的东西:Papa Parse

Papa.unparse(data[, config])

然后将此与本地下载解决方案之一结合起来,例如。 @ArneHB的那个看起来不错。

答案 12 :(得分:3)

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"/*, ...*/]]
  )
);

如果有人需要这个,那么react-csv就是那个

答案 13 :(得分:3)

您可以使用下面的代码使用Javascript将数组导出到CSV文件。

这也处理特殊字符部分

df['cum_sum'] = df["val1"].cumsum()
df['cum_perc'] = round(100*df.cum_sum/df["val1"].sum(),2)

Here是工作jsfiddle的链接

答案 14 :(得分:1)

上面的答案有效,但请记住,如果您以.xls格式开放,列~~可能会被'\t'而不是','分隔,答案{{ 3}}对我来说效果很好,只要我在数组上使用.join('\t')而不是.join(',')

答案 15 :(得分:1)

这是一个Angular友好版本:

  constructor(private location: Location, private renderer: Renderer2) {}

  download(content, fileName, mimeType) {

    const a = this.renderer.createElement('a');

    mimeType = mimeType || 'application/octet-stream';

    if (navigator.msSaveBlob) {

      navigator.msSaveBlob(new Blob([content], {
        type: mimeType
      }), fileName);
    }
    else if (URL && 'download' in a) {

      const id = GetUniqueID();

      this.renderer.setAttribute(a, 'id', id);
      this.renderer.setAttribute(a, 'href', URL.createObjectURL(new Blob([content], {
        type: mimeType
      })));

      this.renderer.setAttribute(a, 'download', fileName);

      this.renderer.appendChild(document.body, a);

      const anchor = this.renderer.selectRootElement(`#${id}`);

      anchor.click();

      this.renderer.removeChild(document.body, a);
    }
    else {
      this.location.go(`data:application/octet-stream,${encodeURIComponent(content)}`);
    }
  };

答案 16 :(得分:1)

人们正在尝试创建自己的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-有关浏览器支持的讨论,请参见此评论。

答案 17 :(得分:1)

以下是我在Java GWT应用程序中在客户端下载CSV文件的方法。特别感谢Xavier John的解决方案。它已经过验证可以在FF 24.6.0,IE 11.0.20和Chrome 45.0.2454.99(64位)中使用。我希望这能节省一些时间:

public class ExportFile 
{

    private static final String CRLF = "\r\n";

    public static void exportAsCsv(String filename, List<List<String>> data) 
    {
        StringBuilder sb = new StringBuilder();
        for(List<String> row : data) 
        {
            for(int i=0; i<row.size(); i++)
            {
                if(i>0) sb.append(",");
                sb.append(row.get(i));
            }
            sb.append(CRLF);
        }

        generateCsv(filename, sb.toString());
    }

    private static native void generateCsv(String filename, String text)
    /*-{
        var blob = new Blob([text], { 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);
            }
        }
    }-*/;
}

答案 18 :(得分:0)

这是基于接受的答案的修改后的答案,其中数据将来自JSON。

            JSON Data Ouptut:
             0 :{emails: "SAMPLE Co., peter@samplecompany.com"}, 1:{emails: "Another CO. , ronald@another.com"}


            JS:
            $.getJSON('yourlink_goes_here', { if_you_have_parameters}, function(data) {
            var csvContent = "data:text/csv;charset=utf-8,";
            var dataString = '';
             $.each(data, function(k, v) {
                dataString += v.emails + "\n";
             });

            csvContent += dataString;

            var encodedUri = encodeURI(csvContent);
            var link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            link.setAttribute("download", "your_filename.csv");
            document.body.appendChild(link); // Required for FF

            link.click();
        });

答案 19 :(得分:0)

我使用此函数将string[][]转换为csv文件。它引用一个单元格,如果它包含",或其他空格(空格除外):

/**
 * 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上不起作用&lt; 11除非map是polyfilled。

注意:如果单元格包含数字,您可以在cell=''+cell之前添加if (cell.replace...,以便将数字转换为字符串。

或者您可以使用ES6在一行中编写它:

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

答案 20 :(得分:0)

我添加到Xavier Johns函数中,如果需要也包含字段头,但是使用jQuery。 $ .each位需要更改本机javascript循环

function exportToCsv(filename, rows, headers = false) {
    var processRow = function (row) {
        row = $.map(row, function(value, index) {
            return [value];
        });
        var finalVal = '';
        for (var j = 0; j < row.length; j++) {
            if(i == 0 && j == 0 && headers == true){
                var ii = 0;
                $.each(rows[i], function( index, value ) {
                    //console.log(index);
                    var fieldName = index === null ? '' : index.toString();
                    //console.log(fieldName);
                    var fieldResult = fieldName.replace(/"/g, '""');
                    //console.log(fieldResult);
                    if (fieldResult.search(/("|,|\n)/g) >= 0){
                        fieldResult = '"' + fieldResult + '"';
                    }
                    //console.log(fieldResult);
                    if (ii > 0){
                        finalVal += ',';
                        finalVal += fieldResult;
                    }else{
                        finalVal += fieldResult;
                    }
                    ii++;
                    //console.log(finalVal);
                });
                finalVal += '\n';
                //console.log('end: '+finalVal);
            }
            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;
            }else{
                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);
        }
    }
}

答案 21 :(得分:0)

如果任何人需要这个用于淘汰赛js,基本上建议的解决方案就可以了:

HTML:

<a data-bind="attr: {download: filename, href: csvContent}">Download</a>

查看模型:

// for the download link
this.filename = ko.computed(function () {
    return ko.unwrap(this.id) + '.csv';
}, this);
this.csvContent = ko.computed(function () {
    if (!this.csvLink) {
        var data = ko.unwrap(this.data),
            ret = 'data:text/csv;charset=utf-8,';

        ret += data.map(function (row) {
            return row.join(',');
        }).join('\n');

        return encodeURI(ret);
    }
}, this);

答案 22 :(得分:0)

我建议使用类似PapaParse的库: https://github.com/mholt/PapaParse

当前接受的答案存在多个问题,包括:

  • 如果数据包含逗号,则失败
  • 如果数据包含换行符,则失败
  • 如果数据包含引号,它(种类)将失败

答案 23 :(得分:0)

只需尝试一下,这里的一些答案就不能处理unicode数据和带有逗号的数据(例如date)。

function downloadUnicodeCSV(filename, datasource) {
    var content = '', newLine = '\r\n';
    for (var _i = 0, datasource_1 = datasource; _i < datasource_1.length; _i++) {
        var line = datasource_1[_i];
        var i = 0;
        for (var _a = 0, line_1 = line; _a < line_1.length; _a++) {
            var item = line_1[_a];
            var it = item.replace(/"/g, '""');
            if (it.search(/("|,|\n)/g) >= 0) {
                it = '"' + it + '"';
            }
            content += (i > 0 ? ',' : '') + it;
            ++i;
        }
        content += newLine;
    }
    var link = document.createElement('a');
    link.setAttribute('href', 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURIComponent(content));
    link.setAttribute('download', filename);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
};

答案 24 :(得分:0)

下载CSV文件

  let csvContent = "data:text/csv;charset=utf-8,";
  rows.forEach(function (rowArray) {
    for (var i = 0, len = rowArray.length; i < len; i++) {
      if (typeof (rowArray[i]) == 'string')
        rowArray[i] = rowArray[i].replace(/<(?:.|\n)*?>/gm, '');
      rowArray[i] = rowArray[i].replace(/,/g, '');
    }

    let row = rowArray.join(",");
    csvContent += row + "\r\n"; // add carriage return
  });
  var encodedUri = encodeURI(csvContent);
  var link = document.createElement("a");
  link.setAttribute("href", encodedUri);
  link.setAttribute("download", "fileName.csv");
  document.body.appendChild(link);
  link.click();

答案 25 :(得分:0)

如果您正在寻找一个非常快速的解决方案,那么您还可以使用这个小型库,该库将为您创建和下载CSV文件:https://github.com/mbrn/filefy

用法非常简单:

import { CsvBuilder } from 'filefy';

var csvBuilder = new CsvBuilder("user_list.csv")
  .setColumns(["name", "surname"])
  .addRow(["Eve", "Holt"])
  .addRows([
    ["Charles", "Morris"],
    ["Tracey", "Ramos"]
  ])
  .exportFile();

答案 26 :(得分:0)

这个老问题有很多好的答案,但这是另一个简单的选择,它依赖于两个流行的库来完成。一些答案提到了Papa Parse,但针对下载部分推出了自己的解决方案。结合Papa Parse和FileSaver.js,您可以尝试以下操作:

const dataString = Papa.unparse(data, config);
const blob = new Blob([dataString], { type: 'text/csv;charset=utf-8' });
FileSaver.saveAs(blob, 'myfile.csv');

here描述了config的{​​{1}}选项。

答案 27 :(得分:0)

来自react-admin

function downloadCsv(csv, filename) {
    const fakeLink = document.createElement('a');
    fakeLink.style.display = 'none';
    document.body.appendChild(fakeLink);
    const blob = new Blob([csv], { type: 'text/csv' });
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        // Manage IE11+ & Edge
        window.navigator.msSaveOrOpenBlob(blob, `${filename}.csv`);
    } else {
        fakeLink.setAttribute('href', URL.createObjectURL(blob));
        fakeLink.setAttribute('download', `${filename}.csv`);
        fakeLink.click();
    }
};

downloadCsv('Hello World', 'any-file-name.csv');

答案 28 :(得分:0)

简约但功能齐全的解决方案:)

/** Convert a 2D array into a CSV string
 */
function arrayToCsv(data){
  return data.map(row =>
    row
    .map(String)  // convert every value to String
    .map(v => v.replaceAll('"', '""'))  // escape double colons
    .map(v => `"${v}"`)  // quote it
    .join(',')  // comma-separated
  ).join('\r\n');  // rows starting on new lines
}

示例:

let csv = arrayToCsv([
  [1, '2', '"3"'],
  [true, null, undefined],
]);

结果:

"1","2","""3"""
"true","null","undefined"

现在将其下载为文件:


/** Download contents as a file
 * Source: https://stackoverflow.com/questions/14964035/how-to-export-javascript-array-info-to-csv-on-client-side
 */
function downloadBlob(content, filename, contentType) {
  // Create a blob
  var blob = new Blob([content], { type: contentType });
  var url = URL.createObjectURL(blob);

  // Create a link to download it
  var pom = document.createElement('a');
  pom.href = url;
  pom.setAttribute('download', filename);
  pom.click();
}

下载:

downloadBlob(csv, 'export.csv', 'text/csv;charset=utf-8;')

save dialog

resulting file