首页 > 解决方案 > 使用 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();
}

输出类似于以下屏幕截图中的输出。

在此处输入图像描述

标签: javascripthtmlutf-8html-tableexport-to-csv

解决方案


能不能换个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>


推荐阅读