If this is not supported, what is the best mechanism for creating a sheet that has formatted columns?
The json_to_sheet algorithm is pretty simple: for each key of a given row object, determine the corresponding column and write to the appropriate cell. The header row is written at the end.
If you just want to format a specific column, after generating the worksheet with json_to_sheet, find the right column for the field you want then walk the cells of that column and assign the cell's .z number format. For example, to reformat the numbers in the "B" column:
var C = XLSX.utils.decode_col("B"); // 1
var fmt = '$0.00'; // or '"$"#,##0.00_);[Red]\\("$"#,##0.00\\)' or any Excel number format
/* get worksheet range */
var range = XLSX.utils.decode_range(ws['!ref']);
for(var i = range.s.r + 1; i <= range.e.r; ++i) {
/* find the data cell (range.s.r + 1 skips the header row of the worksheet) */
var ref = XLSX.utils.encode_cell({r:i, c:C});
/* if the particular row did not contain data for the column, the cell will not be generated */
if(!ws[ref]) continue;
/* `.t == "n"` for number cells */
if(ws[ref].t != 'n') continue;
/* assign the `.z` number format */
ws[ref].z = fmt;
}
@SheetJSDev
I tried to use your answer but my worksheet[ref] is always undefined even though worksheet as well as ref is not undefined. What could be my mistake?
This doesn't work for ODS files - #1569.
Most helpful comment
The
json_to_sheetalgorithm is pretty simple: for each key of a given row object, determine the corresponding column and write to the appropriate cell. The header row is written at the end.If you just want to format a specific column, after generating the worksheet with
json_to_sheet, find the right column for the field you want then walk the cells of that column and assign the cell's.znumber format. For example, to reformat the numbers in the "B" column: