有没有办法将 Excel 中选择的范围导入我的网络应用程序?

时间:2021-03-02 13:38:26

标签: excel api web jsf office-js

我正在尝试将 excel 中的选定范围导入我的网络应用程序(JSF 和 JavaScript)。

我已经能够通过文件上传导入整个 excel 文件,我还可以复制 excel 文件的内容,将其粘贴到某种文本输入中,然后进行解析。但是当一个 excel 使用另一个 excel 的选定范围时,我真的很想拥有这种行为。

我知道这可能是不可能的,因为出于很好的理由,浏览器的运行时与客户端(运行 excel)是分开的。尽管如此,我只是想检查一下是否有我在网络搜索中没有找到的好主意。

excel 范围选择:

excel range select

1 个答案:

答案 0 :(得分:0)

您可以使用 insertWorkbookFromBase64 API 从另一个工作簿复制工作表。然后您可以通过 API 调用删除其他不相关的内容。

以下是供您参考的示例代码。

async function run() {
  await Excel.run(async (context) => {
    //Excel.InsertWorksheetOptions
    var workbook = context.workbook;

    var options = {
      sheetNamesToInsert: ["sample"],
      positionType: Excel.WorksheetPositionType.end,
      relativeTo: "Sheet1"
    };
    const sheets = context.workbook.worksheets;
    sheets.addFromBase64(
      workbookContents,
      null, // get all the worksheets
      Excel.WorksheetPositionType.end // insert them after the current workbook's worksheets
    );
    await context.sync();
  });
}

async function getFileBase64() {
  const myFile = <HTMLInputElement>document.getElementById("file");
  const reader = new FileReader();

  reader.onload = (event) => {
    // strip off the metadata before the base64-encoded string
    const startIndex = reader.result.toString().indexOf("base64,");
    workbookContents = reader.result.toString().substr(startIndex + 7);
  };

  // read in the file as a data URL so we can parse the base64-encoded string
  reader.readAsDataURL(myFile.files[0]);
}

async function insertWorksheetsFromBase64(workbookContents) {
  Excel.run((context) => {
    //Excel.InsertWorksheetOptions
    var options = { sheetNamesToInsert: [], positionType: Excel.WorksheetPositionType.before, relativeTo: "Sheet2" };

    const sheets = context.workbook.insertWorksheetsFromBase64(workbookContents);
    return context.sync();
  });
}
相关问题