【发布时间】: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