如何用Google Apps Script批量将Google Docs表格行数从20增至40?
批量给Google Docs表格添加行的解决方案
我有一份Google Docs工作表,里面有大量表格,每个表格目前有20个空白行(供20名学生使用),需要把每个表格的空白行增加到40个。手动重复添加行太繁琐,虽然知道可以选中20行右键添加,但要操作所有表格还是很麻烦,想找更高效的方法。
我不懂JavaScript,尝试了下面这段代码:
function myFunction() { for (let table in DocumentApp.getActiveDocument().getTables()) { for (let i = 0; i < 20; i++) { table.insertTableRow(20); } } }
运行后报错:
Error TypeError: table.insertTableRow is not a function
问题原因
你用了for...in循环遍历表格数组,但for...in遍历的是数组的索引(字符串类型),不是表格对象本身。所以变量table其实是类似"0"、"1"这样的字符串,自然没有insertTableRow方法,导致报错。
修正后的代码
改用for...of循环直接遍历表格对象,就能正确调用表格的方法了:
function addRowsToTables() { const doc = DocumentApp.getActiveDocument(); const tables = doc.getTables(); // 遍历文档里的每一个表格 for (const table of tables) { // 循环20次,每次在表格末尾插入一行 for (let i = 0; i < 20; i++) { // getNumRows()获取当前表格的行数,以此作为插入位置,确保新行加在最后 table.insertTableRow(table.getNumRows()); } } }
补充说明
如果希望新行和现有空白行的格式一致,可以改成复制最后一行再插入,这样能保留单元格的格式:
function addRowsToTablesWithFormat() { const doc = DocumentApp.getActiveDocument(); const tables = doc.getTables(); for (const table of tables) { const lastRow = table.getRow(table.getNumRows() - 1); for (let i = 0; i < 20; i++) { // 复制最后一行并插入到表格末尾 table.appendTableRow(lastRow.copy()); } } }
内容的提问来源于stack exchange,提问作者tryingtobeastoic
相关产品推荐
相关产品推荐

