我一直在寻找我制作的php应用程序的JavaScript,该应用程序允许用户将html表导出到csv。所以我找到了这个脚本。但是问题是我使用法语单词,法语单词中有一些字母,例如â,ê,î,ô,û,à,è,è,ù,é,ç,ë,ï,ü,表何时导出这些字母转换为不可读的单词,例如Date DateRéalisé。我试图在脚本中为所有这些字母添加替换行,并且行成功了,但没有成功,因为我也希望导出这些字母。
此脚本位于html中:
<script src="tablecsvexporter.js"></script>
<script>
const table = document.getElementById("table");
const btnExportToCsv = document.getElementById("btnExportToCsv");
btnExportToCsv.addEventListener("click", () => {
const exporter = new TableCSVExporter(table);
const csvOutput = exporter.convertToCSV();
const csvBlob = new Blob([csvOutput], { type: "text/csv" });
const blobUrl = URL.createObjectURL(csvBlob);
const anchorElement = document.createElement("a");
anchorElement.href = blobUrl;
anchorElement.download = "table-export.csv";
anchorElement.click();
setTimeout(() => {
URL.revokeObjectURL(blobUrl);
}, 500);
});
</script>
```
and this is what is in the js file :
```
class TableCSVExporter {
constructor (table, includeHeaders = true) {
this.table = table;
this.rows = Array.from(table.querySelectorAll("tr"));
if (!includeHeaders && this.rows[0].querySelectorAll("th").length) {
this.rows.shift();
}
}
convertToCSV () {
const lines = [];
const numCols = this._findLongestRowLength();
for (const row of this.rows) {
let line = "";
for (let i = 0; i < numCols; i++) {
if (row.children[i] !== undefined) {
line += TableCSVExporter.parseCell(row.children[i]);
}
line += (i !== (numCols - 1)) ? "," : "";
}
lines.push(line);
}
return lines.join("\n");
}
_findLongestRowLength () {
return this.rows.reduce((l, row) => row.childElementCount > l ? row.childElementCount : l, 0);
}
static parseCell (tableCell) {
let parsedValue = tableCell.textContent;
// Replace all double quotes with two double quotes
parsedValue = parsedValue.replace(/"/g, `""`);
parsedValue = parsedValue.replace('á', 'a');
parsedValue = parsedValue.replace('é', 'é');
parsedValue = parsedValue.replace('é', 'é');
parsedValue = parsedValue.replace('í', 'i');
parsedValue = parsedValue.replace('ó', 'o');
parsedValue = parsedValue.replace('ú', 'u');
parsedValue = parsedValue.replace('º', '');
// If value contains comma, new-line or double-quote, enclose in double quotes
parsedValue = /[",\n]/.test(parsedValue) ? `"${parsedValue}"` : parsedValue;
return parsedValue;
}
}
```