代码之家  ›  专栏  ›  技术社区  ›  extremeandy

如何使用officejavascript API确保Excel在线请求小于5MB

  •  0
  • extremeandy  · 技术社区  · 6 年前

    https://github.com/OfficeDev/office-js-docs-reference/issues/354 ).

    我们使用Office JavaScript API将大量数据写入Excel工作表,使用以下代码:

    // Example rows - in our actual code this comes from an API
    const rows = [
      ["Date", "Product", "Sales", "Customers"],
      ["13/03/2020", "Chocolate biscuits", 598.00, 93],
      // ... and many more
    ]
    
    sheet.getRangeByIndexes(0, 0, numRows, numColumns).values = rows;
    

    RichApi.Error: An internal error has occurred.

    生成时,行和列的数目未知;数据的大小取决于外接程序用户运行的查询。

    有没有可靠的方法确保我们的要求不超过限额?

    Excel.run(async context => {
      const sheet = context.workbook.worksheets.add();
    
      // 50% of 5MB: allow 50% of overhead
      const THRESHOLD = 0.5 * (5 * 1000 * 1000);
      let bytes = 0;
    
      // Example rows - in our actual code this comes from an API
      const numColumns = 4;
      const rows = [
        ["Date", "Product", "Sales", "Customers"],
        ["13/03/2020", "Chocolate biscuits", 598.00, 93],
        // ... and many more
      ];
    
      for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
        const row = rows[rowIndex];
        sheet.getRangeByIndexes(rowIndex, 0, 1, numColumns).values = [row];
        bytes += JSON.stringify([row]).length;
    
        if (bytes >= THRESHOLD) {
          await context.sync();
          bytes = 0;
        }
      }
    
      return context.sync();
    }
    

    即使允许50%的开销 context.sync() 他还在扔 RichApi.错误:发生内部错误。 一些数据。也许我可以把这个值设得很低(比如10%),但在大多数情况下效率会很低。我希望有一种更可靠的方法来计算有效负载大小,或者询问officeapi来检查挂起的请求的大小。

    0 回复  |  直到 6 年前
        1
  •  0
  •   ginger jiang    6 年前

    请求有效负载大小与以下各项成比例: -API调用的计数 -对象的计数(例如范围对象) -要设置的值的长度

    所以为了使脚本的效率得到提高,需要尽可能少的优化API调用数。如果要打电话范围值对于每一行,将有更多的有效负载开销。

    下面是一个带有优化API调用的示例,以供参考:

        const newValues = [
      ["Date", "Product", "Sales", "Customers"],
      ["13/03/2020", "Chocolate biscuits", 598.00, 93],
      // ... and many more
    ];
    
    for (let rowIndex = 0; rowIndex < newValues.length;) {
      const row = newValues[rowIndex];
      var bytes = JSON.stringify([row]).length;
      var valuesToSet = [];
      valuesToSet.push(row);
    
      var rowCountForNextBatch = 1;
      for (; (rowIndex + rowCountForNextBatch) < newValues.length; rowCountForNextBatch++) {
        const nextRow = newValues[rowIndex + rowCountForNextBatch];
        bytes += JSON.stringify([nextRow]).length;
    
        if (bytes >= THRESHOLD) {
          break;
        }
        valuesToSet.push(nextRow);
      }
    
      console.log(valuesToSet);
      console.log(rowCountForNextBatch);
      sheet.getRangeByIndexes(rowIndex, 0, rowCountForNextBatch, numColumns).values = valuesToSet;
      await context.sync();
    
      rowIndex += rowCountForNextBatch;
    } 
    
    推荐文章