【问题标题】:Google App Script: Dynamically add new rows in Google SheetsGoogle App Script:在 Google 表格中动态添加新行
【发布时间】:2021-12-16 03:18:21
【问题描述】:

我正在制作一张表格以构建要导入 Shopify 的产品列表。

为此,我有一些基本数据的 pdf(此处无关),我从中构建了一个字符串来抓取产品供应商的网站,并以适合导入 Shopify 的方式格式化数据。

产品有不同数量的图像(1 - 8),所以我试图以一种方式构建我的脚本,如果产品有多个图像,我会尝试在下面添加额外的行并将第一个图像之后的每个图像添加到一个新行中。

这是我的代码:

function iterateThroughRows() {

  // get spreadsheet
  const sheet = SpreadsheetApp.getActive().getSheetByName("MySheet");
  const data  = sheet.getDataRange().getValues();

  // Loop over rows
  data.forEach( (row, rowIndex) => {

    const imageSrcArray = [ /* list of image URLs, fetched from remote server */ ]

    imageSrcArray.forEach( (img, arrayIndex) => {
      if(arrayIndex == 0) { // for the first array item, just add it to the current row
        const imageCell = sheet.getRange(rowIndex + 1, 24)
        imageCell.setValue( imageSrcArray[arrayIndex] )
      } else { // for each array item past the first one, add a new row and enter the value there
        sheet.insertRows(rowIndex)
        const imageCell = sheet.getRange(rowIndex + arrayIndex + 1, 24)
        imageCell.setValue( imageSrcArray[arrayIndex] )
      }
    })

    // adding some more values to other cells

 });
}

因为这实际上不起作用。

我昨天一整天都在做这个,并且有一个使用 insertRowAfter() 的版本,它确实添加了额外的行,但是将它们全部加在一起(即在第一个产品之后会有 15 行,但在其他任何一个之后都没有) .但是由于 Google App Script 没有版本控制,我丢失了那个版本。

我认为问题在于forEach 似乎移动到新创建的行并不断从那里添加内容,而不是移动到最初的下一行。

所以我或多或少在我的智慧的尽头。任何有关如何正确执行此操作的建议将不胜感激。

【问题讨论】:

  • 您是否尝试过使用方法getLastRow() 获取最后一行的内容,然后使用+1?
  • 我试过了,但问题是脚本没有完全填充工作表,但一些值已经存在。话虽如此,我可以重构它,这可能是一个很好的解决方案。

标签: loops google-apps-script google-sheets foreach


【解决方案1】:

我能理解您的沮丧,这确实是因为您在向其添加新行之前 关心根据其版本中的工作表计算行。

所以我的建议是这样做,因为currentRow 允许您跟踪您正在处理的当前行。我还更新了insertRowAfter(),因为我认为这是您真正想要做的。

let currentRow = 1;

data.forEach( (row, rowIndex) => {

    const imageSrcArray = [ "img1URL", "img2URL"]
    if( !imageSrcArray.length ) return

    imageSrcArray.forEach( (img, arrayIndex) => {    
      if( arrayIndex == 0 ){
        sheet.getRange(currentRow, 24).setValue( img )
      } else { 
        sheet.insertRowAfter(currentRow)
        sheet.getRange(currentRow+1, 24).setValue( img )
      }
      
      // New rows in between were created
      currentRow++
    })

 });

【讨论】:

  • 谢谢 Neven,效果很好。我目前正在将它集成到完整的脚本中,这个版本肯定会起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-21
  • 1970-01-01
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多