瀏覽器下載EXCEL

  • 62
  • 0
  • 2020-10-28

瀏覽器輸入

data:application/vnd.ms-excel, 

會自動轉EXCEL

在瀏覽器輸入 : 

data:application/vnd.ms-excel, 

data:application/x-zip-compressed,

data:application/msword,

data:application/vnd.ms-powerpoint,

data:application/pdf,

https://support.sas.com/rnd/web/intrnet/filesrv/examds.html

HTML 轉 CSV : http://jsfiddle.net/terryyounghk/KPEGU/

HTML 轉 EXCEL : https://star1530.pixnet.net/blog/post/352388831-html-%E7%9A%84table%E8%BD%89excel%E6%AA%94

function buildHtmlTable(jsonObj, tb) {
    var columns = CreateFirstTR(jsonObj, tb);
    for (var i = 0; i < jsonObj.length; i++) {
        var row = $('<tr/>');
        for (var colIndex = 0; colIndex < columns.length; colIndex++) {
            var cellValue = jsonObj[i][columns[colIndex]];
            if (columns[colIndex] == "日期") {
                cellValue = new Date(cellValue).toISOString().slice(0, 10);//JS毫秒轉日期格式
            }
            else if (columns[colIndex] == "時間") {
                cellValue = new Date(cellValue).toISOString().slice(0, 16).replace('T', ' ');//JS毫秒轉日期+時間格式
            }
            if (cellValue == null) cellValue = "";
            row.append($('<td/>').html(cellValue));
        }
        $(tb).append(row);
    }
}

function CreateFirstTR(jsonObj, tb) {
    var getColumns = [];
    var tr = $('<tr/>');
    for (var i = 0; i < jsonObj.length; i++) {
        var row = jsonObj[i];
        for (var title in row) {
            if ($.inArray(title, getColumns) == -1) {
                getColumns.push(title);
                tr.append($('<td/>').html(title));
            }
        }
    }
    $(tb).append(tr);
    return getColumns;
}

function DownloadExcel(HtmlTable) {
    console.log("[DownloadExcel]");
    var html = '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8" /><title>excel</title>';
    html += '<table border="1">';
    html += document.getElementById(HtmlTable).innerHTML + '';
    html += '</table>';
    console.log(html);
    window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html));
}

-------------------------------------------------------------------------------------
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <!--Excel-->
        <table id="HtmlTbExcel" border="1"></table>
    </form>
</body>
</html>