问题描述
一旦用户点击按钮,我想生成一个excel表。基本上我想做的就是这里的细节。
I wanted to generate an excel sheet once a user clicks on a button . Basically i want to do exactly what is dicussed here
(Kalle H.Väravas答案)
how to pass html table values to excel sheet cells(Kalle H. Väravas answer )
但是,当我点击按钮时,什么都不会发生。我正在使用Mozilla浏览器。我的代码需要启用ActiveXObject。我需要做一些额外的事来完成。 ?
But somehow nothing happens when i click on the button . I am using Mozilla browser . My code needs ActiveXObject enabled . DO i need to do something extra to get it done . ?
我创建了这个小提琴进行测试。如果这样工作,我会尝试我的真实代码。如果这适用于你,那么也请让我知道。谢谢
I created this fiddle for testing . If this works i will try out my real code . if this works for you then also please let me know . Thanks
代码:
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>
推荐答案
这是答案:由insin
Here is the answer: Export dynamic html table to excel in javascript in firefox browser by 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))
}
})()
这篇关于使用jquery从html表生成excel表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!