Created
August 5, 2015 15:40
-
-
Save lovasoa/d4bdeb7c7fe9bb38e88f to your computer and use it in GitHub Desktop.
Fill docx templates with values from a csv file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
/** | |
@author Ophir LOJKINE | |
@license BSD_3Clause | |
**/ | |
var fs = require('fs'); | |
var csvparse = require('csv-parse'); | |
var DocxTemplater = require('docxtemplater'); | |
var util = require('util'); | |
function tplrep(s, dict) { | |
for (i in dict) { | |
s = s.replace('{' + i + '}', dict[i]); | |
} | |
return s; | |
} | |
function addZeroes(s, n) { | |
while (s.length < n) s = '0' + s; | |
return s; | |
} | |
function createFiller(outfiletpl) { | |
//Load the docx file as a binary | |
var content = fs.readFileSync(outfiletpl,"binary"); | |
return function fill(err, datalist) { | |
if (err) console.error(err); | |
datalist.forEach(function(data, i){ | |
var outfilename = tplrep(outfiletpl, data); | |
if (outfilename === outfiletpl) outfilename = addZeroes(i, 2) + " - " + outfilename; | |
console.log("Generating '"+outfilename+"'..."); | |
var doc=new DocxTemplater(content); | |
doc.setData(data); | |
doc.render(); | |
var buf = doc.getZip().generate({type:"nodebuffer"}); | |
fs.writeFileSync(outfilename,buf); | |
}); | |
} | |
} | |
if (process.argv.length < 4) { | |
console.log("Usage: ./csvfill.js input.csv template.docx"); | |
process.exit(1); | |
} | |
var ifname = process.argv[2]; | |
var tplname = process.argv[3]; | |
var transformer = csvparse({columns:true}, createFiller(tplname)); | |
fs.createReadStream(ifname).pipe(transformer); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment