我想在用户点击按钮后生成一个 Excel 工作表。基本上我想做这里讨论的事情
how to pass html table values to excel sheet cells (Kalle H. Väravas 回答)
JavaScript to export HTML tables to Excel
但是当我点击按钮时不知何故没有任何反应。我正在使用 Mozilla 浏览器。我的代码需要启用 ActiveXObject。我需要做一些额外的事情来完成它吗? ?
我创建这个 fiddle 是为了测试。如果这可行,我将尝试我的真实代码。如果这对你有用,那么也请告诉我。谢谢
代码:
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>
最佳答案
这是答案: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))
}
})()
关于javascript - 使用 jquery 从 html 表生成 excel 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15567086/