繁体   English   中英

Google App Script:在 Google 表格中动态添加新行

[英]Google App Script: Dynamically add new rows in Google Sheets

我正在制作一张表格以构建要导入 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似乎移动到新创建的行并继续从那里添加内容而不是移动到最初的下一行。

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

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

所以我的建议是这样做,因为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++
    })

 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM