使用JavaScript创建和下载数据为excel多个工作表

时间:2017-11-20 10:21:30

标签: javascript excel

我正在尝试手动创建数据,然后以excel方式下载。以下是我的代码,工作正常:

<html>
    <body>
    <a href='#' onclick='clickMe();'>Download Excel</a>
        <script>
            var clickMe = function(data,event) {
                var excel = generate();
                download(excel);
            }

            var generate = function(){
                console.log('excel file exported');
                // EXTRACT VALUE FOR HTML HEADER. 
                var columns= [ 'name', 'desc', 'id','createdOn' ];
                var qrows = [
                    ['Foo', 'programmer','1234','12 Apr 2017 12:34:55'],
                    ['Bar', 'bus driver', '2345','13 Apr 2017 12:34:55'],
                    ['Moo', 'Reindeer Hunter', '3456','14 Apr 2017 12:34:55']
                ];

                 // CREATE DYNAMIC TABLE.
                var table = document.createElement("table");
                table.border = '2px solid black';

                // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
                var tr = table.insertRow(-1); // TABLE ROW.

                var col = columns.map(function(qcol){
                var th = document.createElement("th"); // TABLE HEADER.
                th.bgColor ="#a5a5da";
                th.innerHTML = qcol.toUpperCase();
                tr.appendChild(th);
                return tr;
            });

            var rows = qrows.map(function(qrow, index){
                    tr = table.insertRow(-1);
                    qrow.forEach(function(row){
                    var cell = tr.insertCell(-1);
                    cell.innerHTML = row;
                });
                    return tr;
                });

                return table;
            }//generate ends

            var download = function(content, fileName = 'exportExcel.xls', mimeType = 'application/vnd.ms-excel') {
                const a = (document && document.createElement('a')) || {};

                if (typeof navigator != 'undefined' && navigator.msSaveBlob) { // IE10
                    navigator.msSaveBlob(new window.Blob([ content ], { type: mimeType }), fileName);

                    } else if (typeof window.URL != 'undefined' && 'download' in a) { // html5
                    var table_html = content.outerHTML.replace(/ /g, '%20');
                    a.href = 'data:' + mimeType + ', ' + table_html;
                    a.setAttribute('download', fileName);
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                } else {
                    window.open('data:' + mimeType + ', ' + window.encodeURI(content));
                }
            }//download ends

        </script>
    </body>
</html>

这是它的jsfiddle - https://jsfiddle.net/5oxptwh7/2/

我想添加一个新工作表并使用javascript添加一些数据。 KIndly,请指导我如何在上面的代码中实现这一目标

0 个答案:

没有答案