Make a Table recent export data to Excel's needs, from the Internet to find two corresponding code, I use to use JS to export data to Excel Table in (Method 2) in the second, just start to feel pretty Okay, then I found something was wrong. If the data is 000002, it will become 2 after transferring to Excel.
Description: Some data in my form start with 000.
One of the data is 001, 002, 003,
and then analyze the reason. Use JS to export the table data to Excel. If the td book is pure numbers, it will be in Excel format. Number type, so I think 001 will become 1.
So I searched for the corresponding solution on Baidu on the Internet, and changed the type to String before importing it into Excel.
This is the case on Baidu, add a style='mso-number-format:"@"' to td, like this
<td style='mso-number-format:"\@"'><label class="text">000001</label></td>
I was wondering if I could do the processing in the public method of calling export Excel, and add it to him. I
found that the public method of calling export Excel can be modified in batches, (directly paste the modified code)
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><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!--[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.getElementById(table);
//console打印出table.innerHTML出则是table的页面代码
//根据正则表达式,把style='mso-number-format:"\@"' 塞入td中,将数据转成String
table.innerHTML = table.innerHTML.replace(/<td/g, "<td STYLE='MSO-NUMBER-FORMAT:\\@'");
var ctx = {
worksheet: name || 'Worksheet', table: table.innerHTML };//此时的innerHTML数据可以自己自定义 比如json转化 只要值要数据符合即可
var link = document.createElement("A");
link.href = uri + base64(format(template, ctx));
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
});
After modification: The current data is correct, and the effect you want is obtained.
Checking the Excel source code, it is found that they are all str types.
Record, summarize, share! Learning is always on the way!