簡體   English   中英

如何使用 Office.js 從 Excel 中的多個 NamedItems 獲取格式?

[英]How to get format from multiple NamedItems in Excel with Office.js?

我正在嘗試從 NamedItems 列表中檢索一些格式信息。 基本上,我的電子表格有一些分布在多個工作表中的命名范圍,我想獲取一些格式信息,例如每個命名范圍的字體大小。

這是我到目前為止所擁有的:

async function getRangesAndJson() {
  // 1. Find all prz ranges in file
  let myRanges = await Excel.run(async ctx => {
    const namedRangesInFile = ctx.workbook.names;
    namedRangesInFile.load("items");
    await ctx.sync();
    return namedRangesInFile.items.filter(range => range.name.startsWith("abc_"));
  }).catch(error => {
    console.log("error: " + error);
    if (error instanceof OfficeExtension.Error) {
      console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
  });

  // 2. Extract their formatting in JSON, one by one
  await Excel.run(async function(ctx) {
    for (let index = 0; index < myRanges.length; index++) {
      const namedRange = myRanges[index];
      const range = namedRange.getRange();
    }
    await ctx.sync();
  }).catch(error => {
    console.log("error: " + error);
    if (error instanceof OfficeExtension.Error) {
      console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
  });
}

我不確定該怎么做,特別是因為此操作需要大量循環。 實現這一目標的最佳方法是什么?

在您的代碼中,您從每個命名項目中獲取范圍,如果此范圍的字體相同,則可以使用 range.format.font 從該范圍獲取字體。

  const range = namedRange.getRange();
  range.load(["format/*", "format/fill", "format/borders", "format/font"]);
  await ctx.sync();
  console.log(range.format.font.name);

如果你想為這個范圍內的每個單元格獲取字體名稱,你可能需要使用range.getCellProperties ,請參考這個文檔

順便說一句, 出於性能考慮,我們建議不要將 context.sync 放入循環中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM