如何将 JavaScript 数组信息导出到 csv(在客户端)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14964035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to export JavaScript array info to csv (on client side)?
提问by Sam007
I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8and have all the attribute info in array, which looks like this:
我知道有很多这种性质的问题,但我需要使用 JavaScript 来做到这一点。我正在使用Dojo 1.8并拥有数组中的所有属性信息,如下所示:
[["name1", "city_name1", ...]["name2", "city_name2", ...]]
Any idea how I can export this to CSVon the client side?
知道如何将其导出到CSV客户端吗?
回答by Default
You can do this in native JavaScript. You'll have to parse your data into correct CSV format as so (assuming you are using an array of arrays for your data as you have described in the question):
您可以在本机 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";
});
or the shorter way (using 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");
Then you can use JavaScript's window.openand encodeURIfunctions to download the CSV file like so:
然后您可以使用 JavaScriptwindow.open和encodeURI函数来下载 CSV 文件,如下所示:
var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
Edit:
编辑:
如果你想给你的文件一个特定的名字,你必须做一些不同的事情,因为不支持使用该window.openwindow.open方法访问数据 URI 。为了实现这一点,您可以创建一个隐藏的<a><a>DOM 节点并设置其downloaddownload属性如下: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".
回答by Xavier John
Based on the answers above I created this function that I have tested on IE 11, Chrome 36 and Firefox 29
基于上面的答案,我创建了这个功能,我在 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);
}
}
}
For example: https://jsfiddle.net/jossef/m3rrLzk0/
回答by Arne H. Bitubekk
This solution should work with Internet Explorer 10+, Edge,old and new versions of Chrome, FireFox, Safari, ++
此解决方案适用于Internet Explorer 10+、Edge、旧版和新版Chrome、FireFox、Safari、++
The accepted answer won't work with IE and 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');
Running the code snippet will download the mock data as csv
运行代码片段会将模拟数据下载为 csv
Credits to dandavis https://stackoverflow.com/a/16377813/1350598
感谢 dandavis https://stackoverflow.com/a/16377813/1350598
回答by Uxonith
I came here looking for a bit more RFC 4180 compliance and I failed to find an implementation, so I made a (possibly inefficient) one for my own needs. I thought I would share it with everyone.
我来这里是为了寻求更多的 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');
Hopefully this will help someone out in the future. This combines both the encoding of the CSV along with the ability to download the file. In my example on jsfiddle. You can download the file (assuming HTML 5 browser) or view the output in the console.
希望这会在未来帮助某人。这结合了 CSV 的编码以及下载文件的能力。在我关于jsfiddle 的例子中。您可以下载该文件(假设使用 HTML 5 浏览器)或在控制台中查看输出。
UPDATE:
更新:
Chrome now appears to have lost the ability to name the file. I'm not sure what's happened or how to fix it, but whenever I use this code (including the jsfiddle), the downloaded file is now named download.csv.
Chrome 现在似乎已经失去了命名文件的能力。我不确定发生了什么或如何修复它,但是每当我使用此代码(包括 jsfiddle)时,下载的文件现在都命名为download.csv.
回答by Dzarek
The solution from @Default works perfect on Chrome (thanks a lot for that!) but I had a problem with IE.
@Default 的解决方案在 Chrome 上运行完美(非常感谢!)但我在使用 IE 时遇到了问题。
Here's a solution (works on IE10):
这是一个解决方案(适用于 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")
回答by Monu
In Chrome 35 update, download attribute behavior was changed.
在 Chrome 35 更新中,下载属性行为已更改。
https://code.google.com/p/chromium/issues/detail?id=373182
https://code.google.com/p/chromium/issues/detail?id=373182
to work this in chrome, use this
要在 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();
回答by Serdar Didan
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', 'china'],
['22', '???'],
['23', '日本語'],
])
回答by Glen Thompson
Folks are trying to create their own csv string, which fail on edge cases, e.g. special characters and such, surely this is a solved problem right?
人们正在尝试创建自己的 csv 字符串,但在边缘情况下会失败,例如特殊字符等,这肯定是一个已解决的问题,对吗?
papaparse- use for JSON to CSV encoding. Papa.unparse().
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);
}
}
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.
https://github.com/mholt/PapaParse/issues/175- 请参阅此评论以了解浏览器支持讨论。
回答by Madhulika Mukherjee
There you go :
你去吧:
<!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>
回答by Vignesh Subramanian
You can use the below piece of code to export array to CSV file using Javascript.
您可以使用以下代码段使用 Javascript 将数组导出到 CSV 文件。
This handles special characters part as well
这也处理特殊字符部分
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();
Hereis the link to working jsfiddle
这是工作jsfiddle的链接

