使用Javascript將HTML表格table轉換輸出Excel xlsx、xls、csv、txt電子檔

12 月 18, 2018 | Javascript, | 0 comments

TableExport.js

簡單易用的Javascript插件,允許您只在一行代碼,會自動產生輸出Excel、txt、csv按鈕,快速動態地將HTML表格轉換為Excel電子表格 .xls .xlsx,逗號分隔值.csv和純文本 .txt。

下載和設置

使用<script>標籤手動安裝

要使用此插件,請在HTML文檔的結束標記之前包含jQuery庫,FileSaver.js腳本和 TableExport.js插件<body>

<script src="jquery.js"></script>
<script src="FileSaver.js"></script>
 ...
<script src="tableexport.js"></script>

用Bower安裝

$ bower install tableexport.js

用npm安裝

$ npm install tableexport

加載項:

為了提供Office Open XML SpreadsheetML格式(.xlsx)支持,您必須在 FileSaver.js和 TableExport.js 之前將以下第三方腳本包含到項目中

SheetJS的 xlsx.core.js

<script src="xlsx.core.js"></script>
<script src="FileSaver.js"></script>
 ...
<script src="tableexport.js"></script>

較舊的瀏覽器:

要支持舊版瀏覽器,請在FileSaver.js腳本之前包含Blob.js polyfill。

在Safari為HTML5下載屬性或服務工作者提供本機支持之前,通過包含Blob.js polyfill提供有限xlx和xlsx支持,儘管文件名將始終被標記。Unknown

CSS

默認情況下,TableExport.js利用Bootstrap CSS框架提供增強的表格和按鈕樣式。對於非Bootstrap項目,請使用bootstrap設置為的屬性進行初始化 false。

$("table").tableExport({
    bootstrap: false
});

與Bootstrap一起使用時,有四個自定義類.xlsx, .xls, .csv, .txt為每個可導出的文件類型提供按鈕樣式。

JavaScript

要使用導出插件,只需調用:

new TableExport(document.getElementsByTagName("table"));

// OR simply

TableExport(document.getElementsByTagName("table"));

// OR using jQuery

$("table").tableExport();

可以傳入其他屬性以自定義表,按鈕和導出數據的外觀。

使用Javascript

/* Defaults */
TableExport(document.getElementsByTagName("table"), {
    headers: true,                              // (Boolean), display table headers (th or td elements) in the <thead>, (default: true)
    footers: true,                              // (Boolean), display table footers (th or td elements) in the <tfoot>, (default: false)
        formats: ['xlsx', 'csv', 'txt'],            // (String[]), filetype(s) for the export, (default: ['xlsx', 'csv', 'txt'])
        filename: 'id',                             // (id, String), filename for the downloaded file, (default: 'id')
        bootstrap: false,                           // (Boolean), style buttons using bootstrap, (default: true)
        exportButtons: true,                        // (Boolean), automatically generate the built-in export buttons for each of the specified formats (default: true)
        position: 'bottom',                         // (top, bottom), position of the caption element relative to table, (default: 'bottom')
        ignoreRows: null,                           // (Number, Number[]), row indices to exclude from the exported file(s) (default: null)
        ignoreCols: null,                           // (Number, Number[]), column indices to exclude from the exported file(s) (default: null)
        trimWhitespace: true,                       // (Boolean), remove all leading/trailing newlines, spaces, and tabs from cell text in the exported file(s) (default: false)
        RTL: false                                  // (Boolean), set direction of the worksheet to right-to-left (default: false)
    });

使用jquery

    /* Defaults */
    $("table").tableExport({
        headings: true,                    // (Boolean), display table headings (th/td elements) in the <thead>
        footers: true,                     // (Boolean), display table footers (th/td elements) in the <tfoot>
        formats: ["xls", "csv", "txt"],    // (String[]), filetypes for the export
        fileName: "id",                    // (id, String), filename for the downloaded file
        bootstrap: true,                   // (Boolean), style buttons using bootstrap
        position: "bottom",                // (top, bottom), position of the caption element relative to table
        ignoreRows: null,                  // (Number, Number[]), row indices to exclude from the exported file(s)
        ignoreCols: null,                  // (Number, Number[]), column indices to exclude from the exported file(s)
        ignoreCSS: ".tableexport-ignore",  // (selector, selector[]), selector(s) to exclude from the exported file(s)
        emptyCSS: ".tableexport-empty",    // (selector, selector[]), selector(s) to replace cells with an empty string in the exported file(s)
        trimWhitespace: false              // (Boolean), remove all leading/trailing newlines, spaces, and tabs from cell text in the exported file(s)
    });

請注意,默認情況下,TableExport將為三種不同的文件類型創建導出按鈕xls, csv, txt。您可以通過將formats屬性設置為您選擇的文件類型來選擇要生成的按鈕。

方法

TableExport支持其他方法(getExportData,update,reset和remove)以TableExport在創建後控制實例。

getExportData

    /* get export data */
    var exportData = table.getExportData();     // useful for creating custom export buttons, i.e. when (exportButtons: false)

    /*****************
     ** exportData ***
     *****************
    {
        "export-buttons-table": {
            xls: {
                data: "...",
                fileExtension: ".xls",
                filename: "export-buttons-table",
                mimeType: "application/vnd.ms-excel"
            },
            ...
        }
    };
    */

getFileSize

    var tableId = 'export-buttons-table';
    var XLS = table.CONSTANTS.FORMAT.XLS;

    /* get export data (see `getExportData` above) */
    var exportDataXLS = table.getExportData()[tableId][XLS];

    /* get file size (bytes) */
    var bytesXLS = table.getFileSize(exportDataXLS.data, exportDataXLS.fileExtension);

    /**********************************
     ** bytesXLS (file size in bytes)
     **********************************
    352
    */

update

    /* update */
    table.update({
        filename: "newFile"     // pass in a new set of properties
    });

reset

    /* reset */
    table.reset();             // 對動態產生table更改的表

remove

    /* remove */
    table.remove();            // removes caption and buttons

Demo

相關連結

https://github.com/clarketm/TableExport
https://tableexport.v3.travismclarke.com/