用于excel数据的Javascript代码表
<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]--><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,action) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
window.location.href = uri + base64(format(template, ctx))
}
})();
</script>
动作按钮
<input type="button" class="btn btn-success" value="Export" onclick="tableToExcel('tblConsolidate','Report','Fifth Batch')" />
表设计
<table class="table table-bordered" id="tblConsolidate">
<thead>
<tr>
<th>
Head 1
</th>
<th>
Head 2
</th>
</tr>
</thead>
<tbody style="text-align:center;">
<tr>
<td>
body 1
</td>
<td>
body 2
</td>
</tr>
</tbody>
问题
当上面的表导出到excel函数时,对于小数据很好,但是当行超过800行和列时,几乎有20行或更多的,则显示出错误和导出失败。
有什么问题,为什么会被阻止,我的代码应该修改什么?
发布于 2021-03-30 15:05:54
我也有同样的问题,我通过把它保存成一个小块来解决它。
我相信这个问题是由于达到了数据URL数据的限制(在chrome上是2mb),存储它是因为blob增加了大量的数据限制(2G?)。
这个答案非常有用: https://stackoverflow.com/a/36502388
var tableToExcel = (function () {
var myBlob = new Blob( [table.innerHTML] , {type:'application/vnd.ms-excel'});
var url = window.URL.createObjectURL(myBlob);
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = "export.xls";
a.click();
//adding some delay in removing the dynamically created link solved the problem in FireFox
setTimeout(function() {window.URL.revokeObjectURL(url);},0);
});
//and call the function:
tableToExcel();
发布于 2022-07-07 17:42:39
--我用这个代码解决了它
var tableToExcel = (function () {
var encabezado = '<html><head><meta http-equiv="content-type"
content="text/plain; charset=UTF-8"/><style> table, td {border:thin solid
black} table {border-collapse:collapse}</style></head><body><table>';
var dataTable = table.innerHTML
var piePagina = "</table></body></html>";
var tabla = encabezado + dataTable + piePagina;
var myBlob = new Blob( [tabla] , {type:'text/html'});
var url = window.URL.createObjectURL(myBlob);
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = "export.xls";
a.click();
setTimeout(function() {window.URL.revokeObjectURL(url);},0);
});
https://stackoverflow.com/questions/60483757
复制相似问题