Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

javascript - JS HTML Table to Excel File Download IE

I have a HTML table, I am exporting its content to Excel,This is how I am doing

function CreateExcelSheet() {
            var x = document.getElementById("testTable").rows;
var xls = new ActiveXObject("Excel.Application");
            xls.visible = true;
            xls.Workbooks.Add
            for (i = 0; i < x.length; i++) {
                var y = x[i].cells;
                for (j = 0; j < y.length; j++) {
                    xls.Cells(i + 1, j + 1).Value = y[j].innerText;
                }
            }
            xls.Visible = true;
            xls.UserControl = true;
            return xls;
}

its generating Excel properly, but after generating its opening it, I have to download it after generating. I have no clue how to call window.location.href in this scenario. I have to do this in IE only.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:-

HTML:-

<a  onclick="tableToExcel('table_id', 'SHEET1')" class="btn btn-primary">Export to Excel </a>

JS:-

 <script type="text/javascript">//<![CDATA[ 

        var tableToExcel = (function() {
            var uri = 'data:application/vnd.ms-excel;base64,', template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
                    , base64 = function(s) {
                        return window.btoa(unescape(encodeURIComponent(s)))
                    }
            , format = function(s, c) {
                return s.replace(/{(w+)}/g, function(m, p) {
                    return c[p];
                })
            }
            return function(table, name) {
                if (!table.nodeType)
                    table = document.getElementById(table)
                var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
                window.location.href = uri + base64(format(template, ctx))
            }
        })()
//]]>  
    </script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...