Tuesday, November 10, 2020

Membuat Export Csv dengan Javascript


 1. index.html


<table id="dataTable" class="table">

        <thead>

            <tr>

                <th>Rank</th>

                <th>Name</th>

                <th>Points</th>

                <th>Team</th>

            </tr>

        </thead>

        <tbody>

            <tr>

                <td>1</td>

                <td>Steven Soto</td>

                <td>2,462</td>

                <td>Blue</td>

            </tr>

            <tr>

                <td>2</td>

                <td>Alfred, Hines</td>

                <td>1,930</td>

                <td>Blue</td>

            </tr>

            <tr>

                <td>3</td>

                <td>Jeff, "The Champion" Foster</td>

                <td>1,656</td>

                <td>Red</td>

            </tr>

        </tbody>

    </table>

    <button id="btnExportToCsv" type="button" class="button">Export to CSV</button>

    <script>

        const dataTable = document.getElementById("dataTable");

        const btnExportToCsv = document.getElementById("btnExportToCsv");


        btnExportToCsv.addEventListener("click", () => {

            const exporter = new TableCSVExporter(dataTable);

            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>



2. script.js

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, `""`);


        // If value contains comma, new-line or double-quote, enclose in double quotes

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


        return parsedValue;

    }

}


No comments:

Post a Comment

Menjadi Programmer Bukan Hanya Tentang Coding, Tapi Tentang Mempermudah Kehidupan

Semenjak menjadi seorang programmer, ada satu cara pandang yang perlahan berubah dalam diri saya. Saya mulai berpikir bahwa ilmu pemrograman...