JSFiddle - React, Tailwind, and code Playground

by quochieuu

HTML

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>HTML DOM</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body class="font-sans w-full">
    <div class="p-4">
        <table id="exportMe" class="table">
              <thead>
                <tr>
                  <th scope="col"  data-type="number">#</th>
                  <th scope="col">First</th>
                  <th scope="col">Last</th>
                  <th scope="col">Handle</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <th scope="row">1</th>
                  <td>Mark</td>
                  <td>Otto</td>
                  <td>@mdo</td>
                </tr>
                <tr>
                  <th scope="row">2</th>
                  <td>Jacob</td>
                  <td>Thornton</td>
                  <td>@fat</td>
                </tr>
                <tr>
                  <th scope="row">3</th>
                  <td>Larry</td>
                  <td>the Bird</td>
                  <td>@twitter</td>
                </tr>
              </tbody>
        </table>

        <button class="border-none bg-blue-400 text-white px-3 py-2 mt-4" id="export">Export</button>
    </div>

</body>
</html>

CSS

.table {
        border-collapse: collapse;
    }
    .table, .table th, .table td {
        border: 1px solid #ccc;
    }
    .table th, .table td {
        padding: 0.5rem;
    }

JavaScript

document.addEventListener('DOMContentLoaded', function() {
    const table = document.getElementById('exportMe');
    const exportBtn = document.getElementById('export');

    const toCsv = function(table) {
        // Query all rows
        const rows = table.querySelectorAll('tr');

        return [].slice.call(rows)
            .map(function(row) {
                // Query all cells
                const cells = row.querySelectorAll('th,td');
                return [].slice.call(cells)
                    .map(function(cell) {
                        return cell.textContent;
                    })
                    .join(',');
            })
            .join('\n');
    };

// Download file xuống
    const download = function(text, fileName) {
        const link = document.createElement('a');
        link.setAttribute('href', `data:text/csv;charset=utf-8,${encodeURIComponent(text)}`);
        link.setAttribute('download', fileName);

        link.style.display = 'none';
        document.body.appendChild(link);

        link.click();

        document.body.removeChild(link);
    };

// kết nối tất cả các mảnh lại với nhau
    exportBtn.addEventListener('click', function() {
        // Export to csv
        const csv = toCsv(table);

        // Download it
        download(csv, 'download.csv');
    });
});