我正在使用我在网上找到的代码的这个特定部分,我正在尝试实现它,这个 javascript 获取 html 表格中显示的表格的值并将其转换为 excel 工作表。
但由于某些未知原因,代码的以下部分无法正常工作。它只能在 IE 中使用,我不确定为什么下面的代码不起作用。谁能告诉我这段代码有什么问题并告诉我如何更正这段代码?
<html>
<head>
<script type="text/javascript">
function write_to_excel() {
str="";
var mytable = document.getElementsByTagName("table")[0];
var row_Count = mytable.rows.length;
var col_Count = mytable.getElementsByTagName("tr")[0].getElementsByTagName("td").length;
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");
ExcelSheet.Application.Visible = true;
for(var i=0; i < row_count ; i++)
{
for(var j=0; j < col_Count; j++)
{
str= mytable.getElementsByTagName("tr")[i].getElementsByTagName("td")[j].innerHTML;
ExcelSheet.ActiveSheet.Cells(i+1,j+1).Value = str;
}
}
}
</script>
</script>
</head>
<body>
<input type="submit" value="Export to EXCEL" onclick="write_to_excel();"/>
<!-- ************************************************-->
<!--**** INSERT THE TABLE YOU WANT EXPORT HERE ****-->
<table><tr><td>First</td><td>second</td></tr></table>
<!-- *******************example given above****************-->
</body>
</html>
最佳答案
这就是诀窍:
function writeToExcel() {
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;
}
您的原始代码确实有效,for(i)
循环中只有一个拼写错误(row_count == undefined
)。而且没有错误?然而,使用这段代码,您可以摆脱在行中引用单元格的可怕黑客攻击,它还会打开一个“工作簿”而不是“对象”。
关于javascript - html 表格到 javascript 中的 excel 工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11825566/