我知道有很多这种性质的问题,但我需要使用 JavaScript 来做到这一点。我正在使用Dojo 1.8
并拥有数组中的所有属性信息,如下所示:
[["name1", "city_name1", ...]["name2", "city_name2", ...]]
知道如何将其导出到CSV
客户端吗?
我知道有很多这种性质的问题,但我需要使用 JavaScript 来做到这一点。我正在使用Dojo 1.8
并拥有数组中的所有属性信息,如下所示:
[["name1", "city_name1", ...]["name2", "city_name2", ...]]
知道如何将其导出到CSV
客户端吗?
您可以在本机 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");
然后您可以使用 JavaScriptwindow.open
和encodeURI
函数来下载 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".
根据上面的答案,我创建了这个我在 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);
}
}
}
此解决方案应适用于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
我来这里是为了寻找更多的 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
.
在 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();
@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")
一个简约但功能完整的解决方案:)
/** 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;')
人们正在尝试创建自己的 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 - 请参阅此评论以了解浏览器支持讨论。
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 的链接
你去:
<!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>
老问题有很多很好的答案,但这是另一个简单的选择,它依赖于两个流行的库来完成它。一些答案提到了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');
的config
选项在此处unparse
描述。
//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
这里有很多自己动手的解决方案,用于将数据转换为 CSV,但几乎所有这些解决方案都会在数据类型方面有各种警告,因为它们将正确格式化而不会出错 Excel 等。
为什么不使用经过验证的东西:Papa Parse
Papa.unparse(data[, config])
然后只需将其与此处的本地下载解决方案之一结合使用,例如。@ArneHB 的那个看起来不错。
这里有两个问题:
这里对第一个问题的所有答案(除了 Milimetric 的答案)似乎都是矫枉过正。而且 Milimetric 的一个不涵盖替代要求,例如用引号包围字符串或转换对象数组。
以下是我对此的看法:
对于一个简单的 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')
另一方面,如果您想正确执行此操作并将字符串括在引号“”中,那么您可以使用一些 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, '');
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"/*, ...*/]]
)
);
下面是一个原生的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 数据创建一个 blob。即var blob = new Blob([data], type:"text/csv");
如果浏览器支持保存 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();
}
从反应管理员:
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');
以下是我在 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);
}
}
}-*/;
}
上面的答案有效,但请记住,如果您以 .xls 格式打开,列~~可能~~用'\t'
而不是分隔','
,答案https://stackoverflow.com/a/14966131/6169225效果很好对我来说,只要我.join('\t')
在数组上使用而不是.join(',')
.
这是一个 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)}`);
}
};
我使用此函数将一个转换string[][]
为 csv 文件。它引用一个单元格,如果它包含 a "
、 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
}
注意map
:除非是 polyfill ,否则在 Internet Explorer < 11 上不起作用。
注意:如果单元格包含数字,您可以在cell=''+cell
前面添加if (cell.replace...
以将数字转换为字符串。
或者你可以使用 ES6 将它写在一行中:
t.map(r=>r.map(c=>c.replace(/ /g, '').match(/[\s,"]/)?'"'+c.replace(/"/g,'""')+'"':c).join(',')).join('\n')
只需尝试一下,这里的一些答案不处理 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);
};
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();
如果您正在寻找一个非常快速的解决方案,您还可以给这个小型库一个机会,它将为您创建和下载 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();
如果有人需要这个来淘汰 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);
如果需要,我添加到 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();
});