如何通过Google Apps Script将新幻灯片添加至Google Slides末尾?
解决Google Slides从Sheets导入时将新幻灯片添加到末尾的问题
你的核心问题是masterSlide.duplicate()会把新幻灯片插入到模板页的后面,导致新内容插在原有幻灯片之前。要实现把新幻灯片加到演示文稿末尾,不需要用duplicate(),而是通过获取模板的布局,用appendSlide()方法直接在末尾添加新幻灯片,同时可以去掉原来为了纠正顺序而做的数组反转操作。
修改后的完整代码
// Replace <INSERT_SLIDE_DECK_ID> wih the ID of your // Google Slides presentation. let masterDeckID = "SLIDE_DECK_ID"; // Open the presentation and get the slides in it. let deck = SlidesApp.openById(masterDeckID); let slides = deck.getSlides(); // The 2nd slide is the template that will be duplicated // once per row in the spreadsheet. let masterSlide = slides[1]; // 获取模板幻灯片的布局,用于后续创建相同样式的新幻灯片 let templateLayout = masterSlide.getLayout(); // Load data from the spreadsheet. let dataRange = SpreadsheetApp.getActive().getSheetByName('Sheet1').getDataRange(); let sheetContents = dataRange.getValues(); // Save the header in a variable called header let header = sheetContents.shift(); // Create an array to save the data to be written back to the sheet. // We'll use this array to save links to the slides that are created. let updatedContents = []; // 移除原有的反转逻辑:现在新幻灯片直接加到末尾,行顺序和幻灯片顺序一致,不需要反转 // sheetContents.reverse(); // For every row, create a new slide by duplicating the master slide // and replace the template variables with data from that row. sheetContents.forEach(function (row) { // 替换原有的duplicate(),改为在演示文稿末尾添加使用模板布局的新幻灯片 let slide = deck.appendSlide(templateLayout); // Populate data in the slide that was created slide.replaceAllText("{{firstName}}", row[0]); slide.replaceAllText("{{lastName}}", row[1]); slide.replaceAllText("{{grade}}", row[2]); // Create the URL for the slide using the deck's ID and the ID // of the slide. let slideUrl = `https://docs.google.com/presentation/d/${deck.getId()}/edit#slide=id.${slide.getObjectId()}`; // Add this URL to the 4th column of the row and add this row // to the data to be written back to the sheet. row[3] = slideUrl; updatedContents.push(row); }); // Add the header back (remember it was removed using // sheetContents.shift()) updatedContents.unshift(header); // 这里改成unshift,直接把表头加到数组开头,不需要再反转整个数组 // 移除原有的反转逻辑 // updatedContents.reverse(); // Write the updated data back to the Google Sheets spreadsheet. dataRange.setValues(updatedContents); // Remove the master slide if you no longer need it. //masterSlide.remove();
关键改动说明
- 获取模板布局:通过
masterSlide.getLayout()拿到模板幻灯片的布局样式,确保新创建的幻灯片和模板完全一致 - 末尾添加幻灯片:用
deck.appendSlide(templateLayout)替代masterSlide.duplicate(),直接把新幻灯片插入到演示文稿的最后位置 - 简化数组操作:去掉两次
reverse()调用,因为现在表格的行顺序和生成的幻灯片顺序完全对应,表头直接用unshift()加到数组开头即可,无需再反转整个数组
这样修改后,新幻灯片就会按表格行的顺序,依次添加到演示文稿的末尾,最终顺序就是:标题页、模板页、幻灯片1、幻灯片2、[新幻灯片1]、[新幻灯片2]...
内容的提问来源于stack exchange,提问作者Mee
相关产品推荐
相关产品推荐

