我发现这是关于如何使用javascript将单个表导出到excel文件中,并且它适用于一个表:
HTML Table to Excel Javascript
但是,我有多个表要导出到一个CSV文件中。我怎样才能修改代码来实现这个目标?
我尝试将“getElementById”更改为“getElementByClass”,并为这些表添加了相同的类名,但excel输出只是说“undefined”
这是我试过的代码
<script type="text/javascript">
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, filename) {
if (!table.nodeType) table = document.getElementByClass(table)
var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
document.getElementById("dlink").href = uri + base64(format(template, ctx));
document.getElementById("dlink").download = filename;
document.getElementById("dlink").click();
}
})()</script>
<a id="dlink" style="display:none;"></a>
<input type="button" onclick="tableToExcel('alltables', 'alltables', 'myfile.xls')" value="Export to Excel">
print "<table id='vmax' class='alltables'>";
print "<caption>VMAX - 3720</caption>";
print "<tr>";
print "<th>Date</th>";
print "<th>Type</th>";
print "<th>Serial</th>";
print "<th>Total Size</th>";
print "<th>Used</th>";
print "<th>Free</th>";
print "<th>Use %</th>";
print "</tr>";
while($row = sqlsrv_fetch_array($stmt))
{
print "<tr>";
$date = $row[0];
$result = $date->format('Y-m-d');
print "<td>" . $result . "</td>";
for($i=1; $i<6; $i++)
{
print "<td>" . $row[$i] . "</td>";
}
print "<td>" . $row[6]*100 . "%</td>";
print "</tr>";
}
print "</table>";
print "<table id='datadomain' class='alltables'>";
print "<caption>DataDomain - Enterprise Vault</caption>";
print "<tr>";
print "<th>Date</th>";
print "<th>Type</th>";
print "<th>Location</th>";
print "<th>CTWDD</th>";
print "<th>CSC</th>";
print "<th>Total Size</th>";
print "<th>Used</th>";
print "<th>Free</th>";
print "<th>Use %</th>";
print "</tr>";
while($row = sqlsrv_fetch_array($stmt))
{
print "<tr>";
$date = $row[0];
$result = $date->format('Y-m-d');
print "<td>" . $result . "</td>";
for($i=1; $i<8; $i++)
{
print "<td>" . $row[$i] . "</td>";
}
print "<td>" . $row[8]*100 . "%</td>";
print "</tr>";
}
print "</table>";
代码在正确的php标签内,我只是把它留下了,因为还有更多的表。