You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在已有React项目中导入并使用Office.js开发Word Add-in

Using Office.js APIs like 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:

  1. Add the Office.js script to your public HTML
    Open your public/index.html file 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-js package isn’t meant to be imported as a runtime module. The global Office object will be available once the CDN script loads.
  • Always wait for Office.onReady(): If you try to call Office.context before initialization, you’ll get an "Office is not defined" error. The onReady() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 20:54:11