Outline
Export excel files commonly used front-end library is sheetjs . Today PM raised a demand that all the digits using the digital format, in particular, the percentage also use digital format. I think for a long time finally resolved, recorded during a reference for future development, we believe it is useful to others.
problem
By looking at the official documentation of sheetjs , we can see that it supports these types of export formats: Boolean, Error, Number, Date , Text, Stub, there is no percentage format, how to do it?
The method used is 0.00% to format digital format, which is behind two custom 0 2 decimal places, can be more or less applied.
Source
Show me the code:
const workbook = XLSX.utils.book_new();
const sheet = XLSX.utils.json_to_sheet(data);
Object.keys(sheet).forEach((item) => {
const cell = sheet[item];
const value = cell.v;
if (cell.t === 's' && value.indexOf('%') > -1) {
cell.z = '0.00%';
cell.t = 'n';
cell.v = Number(value.substring(0, value.length - 1)) / 100;
}
});
XLSX.utils.book_append_sheet(workbook, sheet, 'Sheet1');
XLSX.writeFile(workbook, filename);
Digression
- This library is really powerful, you can also customize many other things.
- Amway what I wrote it myself excel export library download-excel