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

基于TypeScript、React与Word API开发插件:本地docx文件打开功能疑问

解决Word加载项打开本地文档的问题

首先明确:Word API的createDocument(base64File)方法必须传入文档内容的Base64字符串,无法直接使用本地文件路径(受Office加载项的安全沙箱限制,加载项不能直接读取本地文件系统,必须通过用户主动选择文件的方式获取)。

实现步骤

  • 第一步:通过文件选择器让用户主动选择本地docx文件(不能硬编码路径,必须用户交互)
  • 第二步:将选中的文件转换为Base64字符串
  • 第三步:调用createDocument传入Base64字符串,再执行open()打开文档

完整实现代码

import { useRef } from 'react';

const WordAddInComponent = () => {
  // 用于触发文件选择的隐藏input引用
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file || file.type !== 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
      alert('请选择有效的docx文件');
      return;
    }

    // 将文件转换为纯Base64字符串
    const base64 = await fileToBase64(file);

    // 调用Word API创建并打开文档
    try {
      await Word.run(async (context) => {
        const newDoc = context.application.createDocument(base64);
        newDoc.open();
        await context.sync();
      });
    } catch (error) {
      console.error('打开文档失败:', error);
      alert('打开文档失败,请检查文件是否有效');
    }

    // 重置文件输入,允许重复选择同一文件
    event.target.value = '';
  };

  // 文件转Base64的工具函数
  const fileToBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        // 去掉Data URL前缀,只保留纯Base64内容
        const base64String = reader.result?.toString().replace(/^data:.+;base64,/, '') || '';
        resolve(base64String);
      };
      reader.onerror = reject;
      reader.readAsDataURL(file);
    });
  };

  return (
    <div>
      <button onClick={() => fileInputRef.current?.click()}>打开本地docx文档</button>
      <input
        ref={fileInputRef}
        type="file"
        accept=".docx"
        style={{ display: 'none' }}
        onChange={handleFileSelect}
      />
    </div>
  );
};

export default WordAddInComponent;

关键说明

  • 安全限制:Office加载项运行在浏览器沙箱中,出于安全考虑,不允许直接访问本地文件系统,必须通过用户主动触发的文件选择操作获取文件,无法直接使用硬编码的本地路径。
  • Base64格式要求:createDocument接收的是纯Base64字符串,不需要包含data:...的Data URL前缀,所以转换时要手动移除。
  • 重复选择处理:重置文件输入的value属性,避免用户重复选择同一文件时无法触发onChange事件。

内容的提问来源于stack exchange,提问作者JesseJames

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 03:52:19