我正在尝试使用JavaScript将表格输出到Excel。由于某种原因,它将输出第一行,即列标题,但它不会获得后续数据行。
这是从php页面获取信息,然后将其输出到表格中的屏幕的代码。
jQuery(document).ready(function () {
range = "30days";
$.ajax({
type: 'POST',
url: 'getHash.php',
data: 'value=' + range,
dataType: 'json',
cache: false,
success: function(result) {
// We get the results back and store details;
hash = result;
//We need to clear the text already on the screen
$("#hashDetails").text("");
$("#hashDetails").append("<br/><br/><table width=1400 align=center id='hashTable'><tr><td align=center width=200><b>UPC</b></td><td align=center width=200><b>TAG</b></td><td align=center width=200><b>SKU</b></td><td align=center width=200><b>PKG</b></td><td align=center width=200><b>LOCATION</b></td><td align=center width=200><b>QUANTITY</b></td><td align=center width=200><b>LAST TIME SHIPPED</b></td></tr>");
for (var i = 0; i < hash.length; i++) {
$("#hashDetails").append("<tr class='bottom'><td width=200 align=center class='bottom'>" + hash[i][0] + "</td><td width=200 align=center class='bottom'>" + hash[i][1] + "</td><td width=200 align=center class='bottom'> " + hash[i][2] +"</td></td><td width=200 align=center class='bottom'> " + hash[i][3] +"</td></td><td width=200 align=center class='bottom'> " + hash[i][4] +"</td></td><td width=200 align=center class='bottom'> " + hash[i][5] +"</td></td><td width=200 align=center class='bottom'> " + hash[i][6] +"</td></tr>");
}
$("#hashDetails").append("</table>");
} ,
});
$('input[type=radio]').live('change', function() { alert('error'); });
});
这是将表导出到Excel的代码:
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]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></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))
}
})()
在大多数情况下,它确实有效,因为它会将Excel电子表格下载到客户的计算机上。当我尝试打开电子表格时,它说:
“您尝试打开的文件download.xls的格式与文件扩展名指定的格式不同。在打开文件之前,请验证文件是否已损坏且来自受信任的来源。是否要现在打开文件?“
如果我单击是,它将打开文件,其中只包含第1行中的列标题:
UPC TAG SKU PKG位置数量最后一次发货