在 JavaScript 中导出带有 # 字符的 CSV 数据不起作用
Export CSV data with # character in JavaScript does not work
我将 JSON 数据导出为 CSV 格式并使用 JavaScript 下载。一切正常,除非数据有井号#。函数不导出所有数据,例如:
this is my first C# lesson in the academy, it exports only this is my first C and ignore the rest of it.
这是我的代码
this.handleRow = function (row) {
var finalVal = '';
for (var j = 0; j < row.length; j++) {
var innerValue = "";
if (row[j]) {
innerValue = 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';
};
this.jsonToCsv = function (filename, rows) {
var csvFile = '';
for (var i = 0; i < rows.length; i++) {
csvFile += this.handleRow(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 = $window.document.createElement("a");
if (typeof link.download === "string") {
link.setAttribute("href", "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvFile));
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
$window.document.body.appendChild(link);
link.click();
$window.document.body.removeChild(link);
}
}
};
encodeURI
编码 URI 中禁止使用的字符,而不是具有特殊含义的字符。
#
不会被编码,但它会启动 URI 的片段标识符部分。
改用encodeURIComponent
。
我将 JSON 数据导出为 CSV 格式并使用 JavaScript 下载。一切正常,除非数据有井号#。函数不导出所有数据,例如:
this is my first C# lesson in the academy, it exports only this is my first C and ignore the rest of it.
这是我的代码
this.handleRow = function (row) {
var finalVal = '';
for (var j = 0; j < row.length; j++) {
var innerValue = "";
if (row[j]) {
innerValue = 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';
};
this.jsonToCsv = function (filename, rows) {
var csvFile = '';
for (var i = 0; i < rows.length; i++) {
csvFile += this.handleRow(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 = $window.document.createElement("a");
if (typeof link.download === "string") {
link.setAttribute("href", "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvFile));
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
$window.document.body.appendChild(link);
link.click();
$window.document.body.removeChild(link);
}
}
};
encodeURI
编码 URI 中禁止使用的字符,而不是具有特殊含义的字符。
#
不会被编码,但它会启动 URI 的片段标识符部分。
改用encodeURIComponent
。