docxtemplater
docxtemplater copied to clipboard
XLSX Module : create new sheets in workbook with a simple loop
Environment
- Version of docxtemplater : 3.19.6
- Used docxtemplater-modules : "docxtemplater-xlsx-module"
- Runner : Browser
How to reproduce my problem :
My template is the following (rename template.xlsx) : template.zip
With the following js file :
var fs = require('fs');
var Docxtemplater = require('docxtemplater');
var XlsxModule = require("./docxtemplater-xlsx-module");
var xlsxModule = new XlsxModule({});
//Load the docx file as a binary
var content = fs
.readFileSync(__dirname + "/template.zip", "binary");
var zip = new PizZip(content);
var doc=new Docxtemplater()
doc.attachModule(xlsxModule)
doc.loadZip(zip)
//set the templateVariables
doc.setData({
name: "John Doe",
totalPrice: {
type: "currency",
value: 100,
},
discount: {
type: "percent",
value: 0.195,
},
items: [
{
name: "First product",
quantity: 1,
unit_price: { type: "currency", value: 200 },
},
{
name: "Other product",
quantity: 3,
unit_price: { type: "currency", value: 100 },
},
],
};);
//apply them (replace all occurences of {first_name} by Hipp, ...)
doc.render();
var buf = doc.getZip()
.generate({type:"nodebuffer"});
fs.writeFileSync(__dirname+"/output.docx",buf);
I would expect it to return the following template, with new sheets created inside the workbook: generated.zip
With the module pptx-slides, we can create new slides inside a pptx template with a simple loop.
It would be a great improvement to create new sheets inside an Excel Workbook with the same kind of syntax.
Hello, this is definitely a feature that I will add sometime.
Right now, I have a lot of priorities and not enough time, so it will have to wait.
For the API, I'm not sure the loop would be directly in the sheetname, like you did here :
Maybe this could be a tag like what we do for the slides module :
{:repeat-sheet items}
Also, I'm not sure yet how to handle the names of the generated sheetnames.
Maybe requiring to have a datastructure like this :
{
items: [
{
sheet: "Item Foo",
data: {
name: "First product",
quantity: 1,
unit_price: { type: "currency", value: 200 },
},
},
{
sheet: "Item Bar",
data: {
name: "Other product",
quantity: 3,
unit_price: { type: "currency", value: 100 },
},
},
];
}
To generate two sheets named Item Foo
and Item Bar