<!DOCTYPE html>
<html>
<head>
    <title>JSON to Excel</title>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.8/xlsx.full.min.js'></script>
</head>
<body>
    <h1>JSON to Excel</h1>
    <button onclick='exportToExcel()'>Export to Excel</button>
    <table id='data-table'>
        <thead>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>John Doe</td>
                <td>30</td>
                <td>johndoe@example.com</td>
            </tr>
            <tr>
                <td>Jane Smith</td>
                <td>25</td>
                <td>janesmith@example.com</td>
            </tr>
            <tr>
                <td>Mark Johnson</td>
                <td>35</td>
                <td>markjohnson@example.com</td>
            </tr>
        </tbody>
    </table>
    <script>
        function exportToExcel() {
            var jsonData = [];
            var headers = [];
            $('#data-table thead th').each(function () {
                headers.push($(this).text());
            });
            $('#data-table tbody tr').each(function () {
                var row = {};
                $(this).find('td').each(function (index) {
                    var header = headers[index];
                    row[header] = $(this).text();
                });
                jsonData.push(row);
            });
            var worksheet = XLSX.utils.json_to_sheet(jsonData);
            var workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
            var wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });
<pre><code>        function s2ab(s) {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i &lt; s.length; i++) view[i] = s.charCodeAt(i) &amp; 0xFF;
            return buf;
        }

        saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), 'data.xlsx');
    }
&lt;/script&gt;
</code></pre>
</body>
</html>
JSON to Excel: Convert Your Data with JavaScript

原文地址: https://www.cveoy.top/t/topic/qEQP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录