javascript - 使用 JavaScript 将 HTML 表转换为 CSV 时出现英镑符号 (£) 编码问题
问题描述
我在表头(th)中使用英镑符号(£),我正在使用 javascript 以 CSV 格式导出表。但 CSV 文件显示的是英镑 (£) 符号,如“ £ ”。我尝试了 SO 线程中提供的各种解决方案。但他们都没有为我工作。我该如何解决这个问题?
下面是表格的代码:
<thead>
<tr>
<th>Property Name</th >
<th>Description</th >
<th>Category</th>
<th>Sub category</th>
<th>Amount</th>
<th>Unit</th>
<th> £ / Unit</th>
<th>Sub Total</th>
</tr>
</thead
我正在使用下面的 JavaScript 函数将表格导出为 CSV。
function exportTableToCSV(filename,userName) {
var csv = [];
var rows = document.querySelectorAll("table#"+userName+" tr");
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
downloadCSV(csv.join("\n"), filename);
}
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
csvFile = new Blob([csv], {type: "text/csv"});
downloadLink = document.createElement("a");
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(csvFile);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
输出类似于以下屏幕截图中的输出。
解决方案
能不能换个js看看。
function exportTableToCSV(filename, userName) {
var csv = [];
var rows = document.querySelectorAll("table#" + userName + " tr");
for (var i = 0; i < rows.length; i++) {
var row = [],
cols = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cols.length; j++)
row.push(cols[j].innerText);
csv.push(row.join(","));
}
downloadCSV(csv.join("\n"), filename);
}
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
var csvString = csv;
var universalBOM = "\uFEFF";
var a = window.document.createElement('a');
a.setAttribute('href', 'data:text/csv; charset=utf-8,' + encodeURIComponent(universalBOM + csvString));
a.setAttribute('download', filename);
window.document.body.appendChild(a);
a.click();
}
exportTableToCSV('test.csv', 'velu');
<table id="velu">
<thead>
<tr>
<th>Property Name</th>
<th>Description</th>
<th>Category</th>
<th>Sub category</th>
<th>Amount</th>
<th>Unit</th>
<th> £ / Unit</th>
<th>Sub Total</th>
</tr>
</thead>
</table>
推荐阅读
- r - R如何将函数作为字符串传递给另一个函数
- javascript - Display Api in ReactJs
- sql-server - 有没有办法以 0.0000001 秒的完全精度将当前时间作为 datetime2(7) 获取?
- r - 如何在 Else 部分打印 if else 语句?
- r - 在 R 中:按列中的每个唯一 ID 运行回归,每个唯一 ID 有多个观察值
- node.js - 如何在 Cloudinary 上上传两个名称不同的图像(不是数组)?
- c++ - 如何在 MSYS/MINGW 上使用 autoconf 制作配置脚本?
- excel - 在 Matlab 中定义一条 N% 的数据在其自身之下的曲线
- ruby-on-rails - 在 Rails 中通过 has_many 添加附加属性
- java - 如何使用用户输入来重复程序?