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

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

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

任何想法我怎么能导出到CSV在客户端?

900192 次浏览

你可以在本机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";
});

或者更短的方法(使用箭头函数):

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

编辑:

如果你想给你的文件一个特定的名称,你必须做一些不同的事情,因为这不支持使用window.open方法访问数据URI。为了实现这一点,你可以创建一个隐藏的<a> DOM节点并设置其download属性,如下所示:

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


link.click(); // This will download the data file named "my_data.csv".

@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")

我来这里寻找更多的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示例中。您可以下载文件(假设超文本标记语言为5浏览器)或在控制台中查看输出。

更新:

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

在更新Chrome35中,下载属性行为已更改。

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

根据上面的答案,我创建了这个功能,我已经在IE 11,Chrome36和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/

此解决方案应与Internet Explorer 10+,边缘,旧版本和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格式下载模拟数据

图片来源:Dandavishttps://stackoverflow.com/a/16377813/1350598

使用csv数据. ievar 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();
}

以下是我如何在我的JavaGWT应用程序中下载客户端的CSV文件。特别感谢Xavier John的解决方案。它已被验证在FF 24.6.0、IE 11.0.20和Chrome45.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);
}
}
}-*/;
}

你去那里:

<!doctype html>
<html>
<head></head>
<body>
<a href='#' onclick='downloadCSV({ filename: "stock-data.csv" });'>Download CSV</a>


<script type="text/javascript">
var stockData = [
{
Symbol: "AAPL",
Company: "Apple Inc.",
Price: "132.54"
},
{
Symbol: "INTC",
Company: "Intel Corporation",
Price: "33.45"
},
{
Symbol: "GOOG",
Company: "Google Inc",
Price: "554.52"
},
];


function convertArrayOfObjectsToCSV(args) {
var result, ctr, keys, columnDelimiter, lineDelimiter, data;


data = args.data || null;
if (data == null || !data.length) {
return null;
}


columnDelimiter = args.columnDelimiter || ',';
lineDelimiter = args.lineDelimiter || '\n';


keys = Object.keys(data[0]);


result = '';
result += keys.join(columnDelimiter);
result += lineDelimiter;


data.forEach(function(item) {
ctr = 0;
keys.forEach(function(key) {
if (ctr > 0) result += columnDelimiter;


result += item[key];
ctr++;
});
result += lineDelimiter;
});


return result;
}


window.downloadCSV = function(args) {
var data, filename, link;


var csv = convertArrayOfObjectsToCSV({
data: stockData
});
if (csv == null) return;


filename = args.filename || 'export.csv';


if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv);


link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
</script>
</body>
</html>

如果有人需要这个用于击倒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);

这里有两个问题:

  1. 如何将数组转换为csv字符串
  2. 如何将该字符串保存到文件

这里第一个问题的所有答案(除了Milim的那个)似乎都矫枉过正了。Milimeter的那个不包括替代需求,比如用引号包围字符串或转换对象数组。

以下是我对此的看法:

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

    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')

另一方面,如果你想正确地执行它并将字符串括在引号“”中,那么你可以使用一些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, '');

如果需要,我添加到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);
}
}
}

这是一个基于已接受答案的修改答案,其中数据将来自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();
});

上面的答案有效,但请记住,如果您以. xls格式打开,列~~可能~~由'\t'而不是','分隔,答案https://stackoverflow.com/a/14966131/6169225对我来说效果很好,只要我在数组上使用.join('\t')而不是.join(',')

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就在那里

这是一个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)}`);
}
};

这里有很多用于将数据转换为CSV的自行解决方案,但几乎所有这些解决方案都会在正确格式化数据类型方面有各种警告,而不会绊倒Excel等。

为什么不使用经过验证的东西:PapaParse

Papa.unparse(data[, config])

然后只需将其与此处的本地下载解决方案之一相结合。@ArneHB的那个看起来不错。

我使用此函数将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<11,除非map是多边形填充的。

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

或者您可以使用ES6将其写在一行中:

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

适用于所有语言

        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', '日本語'],
])

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

这也处理特殊字符部分

var arrayContent = [["Séjour 1, é,í,ú,ü,ű"],["Séjour 2, é,í,ú,ü,ű"]];
var csvContent = arrayContent.join("\n");
var link = window.document.createElement("a");
link.setAttribute("href", "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvContent));
link.setAttribute("download", "upload_data.csv");
link.click();

这里是工作jsfiddle的链接

简单地尝试一下,这里的一些答案不处理Unicode数据和具有逗号的数据,例如日期。

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);
};

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

帕帕斯-用于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-请参阅此评论以了解浏览器支持讨论。

下载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();

以下是原生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>

如果您正在寻找一个非常快速的解决方案,您也可以给这个小库一个机会,它将为您创建和下载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();

老问题有很多好答案,但这里有另一个简单的选项,它依赖于两个流行的库来完成它。一些答案提到PapaParse,但在下载部分推出他们自己的解决方案。结合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');

unparseconfig选项描述为这里

来自反应管理

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');

一个简约而功能完整的解决方案:)

/** 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;')

保存对话框

结果文件

这个库帮助很大:https://www.npmjs.com/package/json-to-csv-in-browser

它会自动将jsons数组转换为csv文件,它甚至为您提供下载功能,以防您想提示Web用户下载csv文件。 它的工作原理就像一个魅力,只有很少的代码。

import { JsonArray, download } from 'json-to-csv-in-browser'


const arr = [
{name : ` vader`, age : 53},
{name : "what", age : 38},
{name : "ever", age : 22}
]
const jsonArray = new JsonArray(arr);
const str = jsonArray.convertToCSVstring();
download("my.csv", str);

干杯!

编辑:再测试一下,如果你的值上有逗号,它就不起作用了