Create dynamic word documents using DOCX Js, file-saver and data from an EXCEL or JSON
Everything started from a tiny project that I had, they need to create a lot of test documents around (100) and they need the same old template 🤢 and each document has to have the information of an Excel I was really upset about that and then I searched how o create dynamics documents.
If you want to watch the video of all of this the link is here
Then I found this docx I learn a little and then I create my first document and I will show you how…
Hi I updated this POST and I created a new video if you want to check it
and the new video is here too, thank you so much
First we need https://codesandbox.io/ because it has everything I need to create it
then You need to import two dependencies
docx and file-saver then you need to import the modules
Important! the version of the docx have to be 4.7.1 because it has all that we need for now.
import { Document, Packer, Paragrap } from "docx";import { saveAs } from "file-saver";
Next to them the structure
And the index.html
<!DOCTYPE html><html><head><title>Parcel Sandbox</title><meta charset=”UTF-8" /></head><body><div id=”app”></div><button id=”button-word”>Word document in progress!!</button><script src=”src/index.js”></script></body></html>
You only need a button to activate the word creation if you want, I create an event ( that was the button ) and with that event we call the generateWordDocument
document.getElementById("button-word").addEventListener("click", generateWordDocument, false);
Then that function creates the document that we need, I create a new instance of the Document and a paragraph for my document and then I send the doc variable to a new function called saveDocumentToFile and the name of my document.
function generateWordDocument() {//instance
let doc = new Document();// create some paragraphsdoc.createParagraph("This paragraph will be in my new document");//and using this function we can save our file from the browsersaveDocumentToFile(doc, `first.docx`);}
after that the saveDocumentToFile function help us to save the file, received the doc variable with the paragraph and the fileName I created a new instance of the Packer and the mimeType for Microsoft documents then the b Blob containing the Document instance and the mimeType and finally we use the saveAs to export the file
function saveDocumentToFile(doc, fileName) {const packer = new Packer();const mimeType ="application/vnd.openxmlformats-officedocument.wordprocessingml.document";packer.toBlob(doc).then(blob => {const docblob = blob.slice(0, blob.size, mimeType);saveAs(docblob, fileName);});}
And then you have your document
But what happened if we need, I don't know imagine 1 hundred of documents with the same template and the data of an Excel or another data well I’m going to use this tiny table for example and you can use a big one.
You need this page https://www.convertcsv.com/csv-to-json.htm
you can upload your csv or insert the data
And then generate the JSON
With the json we need to create a variable and insert the data in that variable
const fakeDataExcel = [
{"Id": 1,"name": "Michael","country": "England"},{"Id": 2,"name": "Charles","country": "Canada"}]
And we need to create a for loop and inside the for we could insert an auto invoke function with a setTimeout why? Because if you try to run with a lot of data the process is too fast and some documents will be lost trust me I tried
for (let i = 0; i < fakeDataExcel.length; i++) {(function(i) {window.setTimeout(function() {}, i * 2000);})(i);}
And the final part you need to make the dynamic variables and the final code will be this
for (let i = 0; i < fakeDataExcel.length; i++) {(function(i) {window.setTimeout(function() {let doc = new Document();doc.createParagraph(`Id: ${fakeDataExcel[i]['Id']}`);doc.createParagraph(`Name: ${fakeDataExcel[i]['name']}`);doc.createParagraph(`Country: ${fakeDataExcel[i]['country']}`);saveDocumentToFile(doc, `user${fakeDataExcel[i]['name']}-${fakeDataExcel[i]['Id']}.docx`);}, i * 2000);})(i);}
Conclusion
If you need to create too many documents and with dynamic variables this will help you and if you want to make it better the styles will help you too everything is in this part and if you need help I will try to help you đź‘Ť and Thanks for reading.
Sources
https://github.com/dolanmiu/docx/issues/211
https://github.com/dolanmiu/docx/wiki/Examples
https://github.com/dolanmiu/docx/wiki/Styling-with-JS
https://www.iainfreestone.com/how-to-create-a-word-document-with-javascript/
https://www.convertcsv.com/csv-to-json.htm
The complete code :
https://codesandbox.io/s/competent-http-hqr6x?file=/src/index.js
https://codesandbox.io/s/mystifying-mclaren-dls9n?file=/src/index.js
The video
https://youtu.be/4sGg9rmn2EM
Follow me on Twitter @shadowbeat274
https://www.buymeacoffee.com/YdAe1D4
https://github.com/rodrigofigueroa/docxjsexample