我想在用户点击按钮后生成Excel工作表。基本上我想做的就是这里讨论的内容
how to pass html table values to excel sheet cells (KalleH.Väravas回答)
JavaScript to export HTML tables to Excel
但是当我点击按钮时,不知何故没有任何反应。我正在使用Mozilla浏览器。我的代码需要启用ActiveXObject。我需要做一些额外的事情才能完成它。 ?
我创造了这个小提琴进行测试。如果这工作,我会尝试我的真实代码。如果这对你有用,那么请告诉我。谢谢
代码:
JS:
<script type="text/javascript">
function CreateExcelSheet() {
var i, j, str,
myTable = document.getElementById('mytable'),
rowCount = myTable.rows.length,
excel = new ActiveXObject('Excel.Application');// Activates Excel
excel.Workbooks.Add(); // Opens a new Workbook
excel.Application.Visible = true; // Shows Excel on the screen
for (i = 0; i < rowCount; i++) {
for (j = 0; j < myTable.rows[i].cells.length; j++) {
str = myTable.rows[i].cells[j].innerText;
excel.ActiveSheet.Cells(i + 1, j + 1).Value = str; // Writes to the sheet
}
}
return;
}
</script>
Html:
<table id ="myTable" >
<tr>
<td>1</td>
<td>Jan</td>
<td>01/04/2012</td>
<td>Approved</td>
</tr>
<tr>
<td>2</td>
<td>Feb</td>
<td>01/04/2012</td>
<td>Approved</td>
</tr>
</table>
<form>
<input type="button" onclick="CreateExcelSheet();" value="Create Excel Sheet" >
</form>
答案 0 :(得分:16)
以下是答案:Export dynamic html table to excel in javascript in firefox browser由insin
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))
}
})()
答案 1 :(得分:12)
要回答有关IE的问题(由于声誉限制,我无法在评论栏中回答),Sharun发布的上述代码无法在IE 10+上工作(&#39;许可被拒绝&#39;错误)。这是一个可以在IE 10+中使用的片段以及旧版本的IE,Chrome和FF:
<a target="_blank" href="/Home.aspx">...</a>
答案 2 :(得分:1)
$("#btnExport").click(function(e) {
e.preventDefault();
//getting data from table
var data_type = 'data:application/vnd.ms-excel';
var table_div = document.getElementById('table_wrapper');//table_wrapper is table id
var table_html = table_div.outerHTML.replace(/ /g, '%20');
var a = document.createElement('a');
a.href = data_type + ', ' + table_html;
a.download = 'table_name_' + Math.floor((Math.random() * 9999999) + 1000000) + '.xls';
a.click();
});
答案 3 :(得分:0)
您可以使用这个好的库:https://github.com/jmaister/excellentexport