Google 脚本 - 将 Table 中的 Table 单元格修改为每行中的不同列数

Google Scripts - Modify Table Cell in Table with different number of columns in each row

我正在尝试修改具有多行的 google 文档 table,但每行的列数不同。

这是一个例子table

如何使用 table.getCell(row,col) 或 row.getCell(col) 获取 a,b,c,d,e,f,g 等的内容..

寻址每个单元格并修改内容的正确方法是什么。我正在处理的 tables 具有定义的结构。

  tables.forEach(function(table) {
    var numberOfRows = table.getNumRows();
    console.log("New Table with Rows: " + numberOfRows);
    for (var rowIndex = 0; rowIndex < numberOfRows; rowIndex++) {
      var row = table.getRow(rowIndex);
      // this is a table of interest and we know the exact structure
      if(rowIndex == 0 && row.getCell(0).getText().toString().trim().includes("2 cols")){
        row.getCell(0).editAsText().setText("11");
        row.getCell(1).editAsText().setText("12");
      }else if(rowIndex == 1 && row.getCell(0).getText().toString().trim().includes("3 cols")){
        row.getCell(1).editAsText().setText("21");
        row.getCell(2).editAsText().setText("22");
      }else if(rowIndex == 2 && row.getCell(0).getText().toString().trim().includes("5 cols")){
          row.getCell(1).editAsText().setText("31");
          row.getCell(2).editAsText().setText("32");  // NOTE1: THIS IS THE ISSUE
          row.getCell(3).editAsText().setText("33");  // NOTE3: THIS IS THE ISSUE
      }
    }
  })

这是上面代码的 table 输出

为什么NOTE1和NOTE2没有修改单元格e,单元格f?

我认为在您的脚本中,row.getCell(1)row.getCell(2)row.getCell(3)getColSpan() 的值是 300。当getColSpan()的值为0时,表示合并单元格。我认为这可能是您遇到问题的原因。那么,为了达到你的目的,下面的修改怎么样?

发件人:

row.getCell(1).editAsText().setText("31");
row.getCell(2).editAsText().setText("32");  // NOTE1: THIS IS THE ISSUE
row.getCell(3).editAsText().setText("33");  // NOTE3: THIS IS THE ISSUE

收件人:

var nCol = 0;
var values = ["31", "32", "33"];
for (var colIndex = 1; colIndex < row.getNumCells(); colIndex++) {
  var cell = row.getCell(colIndex);
  if (values.length > nCol && cell.getColSpan() > 0) {
    cell.editAsText().setText(values[nCol++]);
  }
}
  • 通过此修改,5 cols 行的值为 5 cols, 31, 32, 33