我知道有很多这种性质的问题,但我需要使用JavaScript来做到这一点。我使用Dojo 1.8并在数组中拥有所有属性信息,它看起来像这样:
[["name1", "city_name1", ...]["name2", "city_name2", ...]]
知道我如何在客户端将此导出为CSV吗?
我知道有很多这种性质的问题,但我需要使用JavaScript来做到这一点。我使用Dojo 1.8并在数组中拥有所有属性信息,它看起来像这样:
[["name1", "city_name1", ...]["name2", "city_name2", ...]]
知道我如何在客户端将此导出为CSV吗?
当前回答
这个解决方案应该适用于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
其他回答
人们尝试创建自己的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 -请参阅此评论了解浏览器支持讨论。
下面是一个原生的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>
老问题,有很多好的答案,但这里有另一个简单的选择,它依赖于两个流行的库来完成。有些回答提到了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');
这里描述了unparse的配置选项。
这里有许多将数据转换为CSV的解决方案,但几乎所有的解决方案都有各种各样的注意事项,即在不出错的情况下正确格式化数据类型。
为什么不使用一些经过验证的东西:Papa Parse
Papa.unparse(data[, config])
然后只需结合这与本地下载解决方案之一在这里,如。@ArneHB的那个看起来不错。
我添加到Xavier Johns函数也包括字段头,如果需要,使用jQuery。美元的。对于原生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);
}
}
}