Javascript HTML表單table輸出Excel

9 月 20, 2018 | | 0 comments

Javascript table 轉 Excel檔案

讀取HTML table 將document.write寫入檔案

function fnExcelReport()
{
    var tab_text=<table border="'2px'"><tr bgcolor="'#87AFC6'">;
    var textRange; var j=0;
    tab = document.getElementById('headerTable'); // id of table

    for(j = 0 ; j ;
        //tab_text=tab_text+</tr>;
    }

    tab_text=tab_text+</table>;
    tab_text= tab_text.replace(/<a>]*>|</a>/g, );//remove if u want links in your table
    tab_text= tab_text.replace(/<img></img>]*>/gi,); // remove if u want images in your table
    tab_text= tab_text.replace(/<input></input>]*>|/gi, ); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf(MSIE ); 

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv:11./))      // If Internet Explorer
    {
        txtArea1.document.open(txt/html,replace);
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa=txtArea1.document.execCommand(SaveAs,true,Say Thanks to Sumit.xls);
    }  
    else                 //other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
} 

範例展示

See the Pen javascript export excel by Leon Cheng (@jq153387) on CodePen.

使用TableExport.js外掛方式輸出檔案

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