将多个html表转换为.csv

时间:2019-10-28 18:37:02

标签: javascript html

我目前有三个表,需要将它们连接在一起,以便可以将它们转换为csv文件。我现在有一个工作版本,可以将一个表转换为csv,但是我正在努力弄清楚如何将另外两个表合并在一起,同时为每个表保留各自的标题。我已经看过使用.appendchild了,但这并没有给我我想要的标题以及querySelector。任何帮助将不胜感激!

const dataTable = document.getElementById("CSVTable");
const btnExportToCSV = document.getElementById("btnExport");
btnExportToCSV.addEventListener("click", () => {
        const exporter = new TableCSVExporter(dataTable);
        const output = exporter.ConvertToCSV();
        const csvBlob = new Blob([output], { type: "text/csv" });
        const blobUrl = URL.createObjectURL(csvBlob);
        const anchor = document.createElement("a");

        anchor.href = blobUrl;
        anchor.download = "Senator-CSV-Report.csv";
        anchor.click();

        setTimeout(() => {
            URL.revokeObjectURL(blobUrl);
        }, 500);
    });

class TableCSVExporter {
    constructor(table, includeHeaders = true) {
        this.table = table;
        this.rows = Array.from(table.querySelectorAll("tr"));

        console.log(this._findLongestRowLength());
    }

    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() {
        var result = this.rows.reduce((l, row) => row.childElementCount > l ? row.childElementCount : l, 0);
        return result;
    }

    static parseCell(tableCell) {
        let parsedValue = tableCell.textContent;

        parsedValue = parsedValue.replace(/"/g, '""');

        parsedValue = /[",\n]/.test(parsedValue) ? '"${parsedValue}"' : parsedValue;

        return parsedValue;
    }
}

0 个答案:

没有答案