如何在已有React项目中导入并使用Office.js开发Word Add-in
getFileAsync() in a React Project Hey there! I’ve worked with React + Office Add-ins before, so let me walk you through how to properly access and use Office.context.document.getFileAsync() and other Office.js methods in your project.
First, Understand How Office.js Loads
Even though you installed @microsoft/office-js via npm, that package primarily provides TypeScript type definitions for IDE intellisense. The actual runtime Office.js library needs to be loaded by the Office host (Word, in your case) or via a CDN. Here’s what to do:
- Add the Office.js script to your public HTML
Open yourpublic/index.htmlfile and add this script tag in the<head>section. This ensures Office.js loads before your React app tries to use it:<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>
Use Office.js Safely in Your React Components
Office.js loads asynchronously, so you need to wait for it to initialize before calling any APIs. Here’s a practical example component:
import React, { useEffect } from 'react'; const WordFileHandler = () => { // Wait for Office to finish initializing when the component mounts useEffect(() => { Office.onReady((info) => { if (info.host === Office.HostType.Word) { console.log("Office is ready to use Word-specific APIs!"); } }); }, []); const handleExtractFile = () => { // Call getFileAsync once Office is initialized Office.context.document.getFileAsync( Office.FileType.Pdf, // Choose the file type you need { sliceSize: 65536 }, // Chunk size for large files (asyncResult) => { if (asyncResult.status === Office.AsyncResultStatus.Succeeded) { const file = asyncResult.value; console.log("Successfully retrieved file:", file); // Don't forget to close the file when you're done! file.closeAsync(); } else { console.error("Error fetching file:", asyncResult.error.message); } } ); }; return ( <div className="add-in-container"> <button onClick={handleExtractFile}>Get Document as PDF</button> </div> ); }; export default WordFileHandler;
Key Notes to Avoid Issues
- Don’t import Office from the npm package: The
@microsoft/office-jspackage isn’t meant to be imported as a runtime module. The globalOfficeobject will be available once the CDN script loads. - Always wait for
Office.onReady(): If you try to callOffice.contextbefore initialization, you’ll get an "Office is not defined" error. TheonReady()method ensures the host environment is ready. - Test in the Office host: You can’t test this directly in a regular React dev server—you need to run it as an Office Add-in. Use tools like the Office Add-in Debugger or Yeoman’s Office Add-in generator to set up proper debugging.
For TypeScript Users
Since you installed @microsoft/office-js, you’ll automatically get type hints for all Office.js APIs in your IDE. No extra imports needed—just use the global Office object, and TypeScript will recognize the types.
内容的提问来源于stack exchange,提问作者UK4

