使用 TypeScript 将文件保存在 Excel 加载项中

问题描述 投票:0回答:1

我使用 TypeScript 中的 Yeoman Generator 创建了一个 Excel 加载项。该加载项提供了一些基本信息,例如通过单击按钮突出显示 Excel 的某些部分、调用外部 API 来处理单元格等。但是,当我尝试使用 fs 或文件保护程序创建和下载新文件时,没有错误消息,也没有下载任何内容。代码如下所示。

import { saveAs } from "file-saver";
import { Document, Packer, Paragraph, TextRun } from "docx";

export const docGenerator = async () => {
  // Documents contain sections, you can have multiple sections per document, go here to learn more about sections
  // This simple example will only contain one section
  const doc = new Document({
    sections: [
      {
        properties: {},
        children: [
          new Paragraph({
            children: [
              new TextRun("Hello World"),
              new TextRun({
                text: "Foo Bar",
                bold: true,
              }),
              new TextRun({
                text: "\tGithub is the best",
                bold: true,
              }),
            ],
          }),
        ],
      },
    ],
  });

  try {

    const blob = await Packer.toBlob(doc);
    console.log(blob);
    saveAs(blob, "example.docx");
    console.log("Document created successfully");
  } catch (error) {
    console.error(error);
  }
};

网络选项卡显示以下消息: enter image description here

我的问题:是否可以在 Office 加载项(例如 Excel 加载项)中创建和保存本地文件?如果不是,原因是什么?有解决方法吗?

我尝试了 fs 和 file-savers 库来保存和下载文件,但据我所知,没有任何内容被保存,控制台中也没有错误消息。

typescript office-js office-addins excel-addins
1个回答
0
投票

这不能在 Office 加载项中完成。加载项是 Web 应用程序,它们面临与 Web 应用程序相同的安全限制。这些限制之一是 Web 应用程序无法访问计算机的本地文件系统,除非某些高度受限的用途(例如保存 cookie)除外。像 fs 这样的库在本地 Nodejs 实例中使用,而不是在 Web 应用程序中使用。

© www.soinside.com 2019 - 2024. All rights reserved.