
How to Open a DOCX File into the Current Document Using OfficeJS
Hi there,
I'm developing a Word Add-in (Taskpane) which the main goal is replace some predefined content controls of documents persisted in a database. This add-in is a web app using Office.JS. Based on some user input the Add-in get the file and open it.
My first approach based in documentation (office) was the following:
fetch(`/arquivo?id=${idModeloDocumento}`)
.then(response => response.text())
.then(base64String => {
Word.run(async context => {
const app = context.application;
const doc = app.createDocument(base64String); // base64string comes from my backend app
doc.open();
await context.sync();
});
})
However, it opens the document on a new instance of Word. That's not comfortable to our users.
First Question: Is there a method to open it in the current document object?
So, as a workaround I didn't open the document. After createDocument method calling, I got body and header Ooxml and inserted into the current document instead.
Like this:
fetch(`/arquivo?id=${idModeloDocumento}`)
.then(response => response.text())
.then(base64String => {
Word.run(async context => {
var base64doc = base64String
const app = context.application
const doc = app.createDocument(base64doc)
await context.sync()
console.log("Novo documento criado")
let bodyOoxml = doc.body.getOoxml()
let headerOoxml = doc.sections.getFirst().getHeader(Word.HeaderFooterType.primary).getOoxml()
await context.sync()
console.log("Preenchendo o body do documento corrente")
let curHeader = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.primary)
curHeader.insertOoxml(headerOoxml.value, Word.InsertLocation.replace)
let curBody = context.document.body
curBody.insertOoxml(bodyOoxml.value, Word.InsertLocation.replace)
await context.sync()
console.log("Pronto")
});
})
It worked, but I'm not 100% sure that's the correct way to do that.
Can you help me? Can you drive me to a documentation or samples where I can learn how to deal with this kind of situation the right way?
Regards,
Marco
Microsoft 365 and Office | Development | Office JavaScript API

Microsoft 365 and Office | Development | Other
