How should I add conditional formatting to some columns in an Excel file that I generate in Node.js? When I add the xml to the worksheet like this answer I get errors in Excel, thought the file opens. I generate the file using xlsx in Node.js so the Excel file looks like this inside:
- Sample.xlsx
- [Content_Types].xml
- ...
- xl
- _rels
- sharedString.xml
- styles.xml
- theme
- workbook.xml
- worksheets
- sheet1.xml
I write my conditional formatting into sheet1.xml, here is the code to do this:
var fs = require("fs");
var jszip = require("jszip");
var CONDITIONAL_FORMATTING = '<conditionalFormatting sqref="A1">' +
'<cfRule type="expression" dxfId="0" priority="1"><formula>LEN(A1)&' +
'gt;2</formula></cfRule></conditionalFormatting>';
var WORKSHEET1 = 'xl/worksheets/sheet1.xml';
fs.readFile("excel/rewrite.xlsx", function(err, data) {
jszip.loadAsync(data).
then(function(zip) {
rezip = zip;
return zip.file(WORKSHEET1).async("string");
}).then(function (worksheet) {
var pos = worksheet.indexOf('<pageMargins');
if(pos > 0) {
worksheet = worksheet.substring(0,pos) +
CONDITIONAL_FORMATTING + worksheet.substring(pos);
}
rezip.file(WORKSHEET1,worksheet);
rezip.generateNodeStream({type:'nodebuffer',streamFiles:true})
.pipe(fs.createWriteStream('out.xlsx'))
.on('finish', function () {
console.log('done');
});
});
});