Word 2016加载项是否支持RESTful调用及文档上传至服务器?
1. Does Word 2016 Add-in support RESTful calls?
Absolutely! Word 2016 add-ins are built on web technologies (HTML, JavaScript, CSS) at their core, which means you have full access to standard web APIs for making RESTful requests. You can use tools like fetch() or XMLHttpRequest to send GET, POST, PUT, DELETE, or any other HTTP method to your backend server.
Office.js (the framework for building Office add-ins) doesn't restrict this capability—in fact, it's common practice to integrate add-ins with external services via REST calls to pull data into the document, push updates, or sync content.
2. Can I send the document to a web server via RESTful call after it's saved?
Yes, you can absolutely do this. Here's a practical breakdown of how to implement it:
- Listen for the document saved event: Use Office.js's
Document.onSavedevent to trigger your code right after the document is saved. - Retrieve the document content: You can get the entire document as a Base64-encoded string using
Word.run()anddocument.getBase64Async(), or extract specific parts if you don't need the full document. - Send the content via REST: Use a
fetch()(or similar) call to POST the document data to your web server.
Here's a quick code snippet to illustrate this flow:
// Initialize Office.js first Office.initialize = function(reason) { // Register the saved event listener Word.run(function(context) { context.document.onSaved.add(sendDocumentToServer); return context.sync(); }).catch(function(error) { console.error("Error registering event: " + error); }); }; function sendDocumentToServer() { Word.run(function(context) { var document = context.document; // Get the document as Base64 return document.getBase64Async().then(function(result) { var docBase64 = result.value; // Send via REST POST request fetch("https://your-server-url.com/api/documents", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ documentName: document.properties.title, content: docBase64 }) }) .then(response => response.json()) .then(data => console.log("Document sent successfully:", data)) .catch(error => console.error("Error sending document:", error)); }); }).catch(function(error) { console.error("Error processing document: " + error); }); }
A few quick notes:
- Ensure your server allows cross-origin requests (CORS) if your add-in is hosted on a different domain than your backend.
- Add robust error handling—network issues, server timeouts, or permission problems can pop up, so don't skip this step.
- If you don't need the full document, Office.js has APIs to access specific parts like selected text or a defined range instead.
内容的提问来源于stack exchange,提问作者Mers_M2

