前端导出excel,先生成一个tabel,加上特定的html协议,拼接成一个html文件,再通过接口转换成文件,a标签模拟点击下载。设置单元格为文本类型方法:一是设置样式vnd.ms-excel.numberformat:@; mso-number-format:@;第二种是在数字后加个一个空格 就不会看出数字了,解决‘000123’导出后变成123的问题
参考网址:https://www.cnblogs.com/heihei-haha/p/7921432.html
注意事项:td里面如果有其它元素,会只提取文本内容,td设置padding样式再excel中无作用,图片不会撑开单元格
//设置单元格为文本类型
td.text-type{
vnd.ms-excel.numberformat:\@;
mso-number-format:\@;
}
//base64转码
var base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)));
};
//替换table数据和worksheet名字
var format = function (s, c) {
return s.replace(/{(\w+)}/g,
function (m, p) {
return c[p];
});
}
function tableToExcel(tableid, sheetName) {
var uri = 'data:application/vnd.ms-excel;base64,';
var 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]-->' +
' <style type="text/css">' +
'#box{width:1200px;}table{width:1000px;border-collapse: collapse;border-spacing: 0;} table td {' +
'border: thin solid #e7e7e7;' +
'width: 10%;' +
'height:40px;' +
' text-align: center;' +
'background-color: #fff;' +
'color: #333;' +
' }' +
'</style>' +
'</head><body ><table class="excelTable" border="1" cellspacing="0" cellpadding="0">{table}</table></body></html>';
$("td").each(function(){
var height = $(this).outerHeight();
var weight = $(this).outerWidth();
$(this).css("height",height + "px");
$(this).css("width",weight + "px");
})
if (!tableid.nodeType) tableid = document.getElementById(tableid);
var ctx = {worksheet: sheetName || 'Worksheet', table: tableid.innerHTML};
document.getElementById("excelOut").href = uri + base64(format(template, ctx));
//document.getElementById("excelOut").click()
}