我正在制作一張表格以構建要匯入 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似乎移動到新創建的行并繼續從那里添加內容而不是移動到最初的下一行。
所以我或多或少在我的智慧的盡頭。任何有關如何正確執行此操作的建議將不勝感激。
uj5u.com熱心網友回復:
我可以理解您的沮喪,這確實是因為您在向其添加新行之前關心根據其版本中的作業表計算行。
所以我的建議是這樣做,因為它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
})
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/343968.html
