Google Script代码修改:如何获取数组全部列而非仅[0,1,2,3]指定列
问题解决思路
核心错误点:你之前用Object.keys(this_table)遍历的是this_table的列索引,this_table总共只有4个元素(对应你提取的4列数据),所以只能生成4行。你实际需要遍历的是筛选后每行的下标,也就是和values_C等列数组长度一致的索引序列。
修改步骤
- 替换原四次遍历筛选的逻辑,一次筛选出所有符合条件的行,同时获取数据总行数,大幅提升运行效率:
// 一次筛选出所有符合条件的行 const ready_rows = table.filter(t => t[7] == "READY TO SELL"); // 获取筛选后的总行数 const row_count = ready_rows.length; // 从筛选结果中提取各列,无需重复遍历原表格 const values_C = ready_rows.map(t => t[0]); const values_D = ready_rows.map(t => t[1]); const values_E = ready_rows.map(t => t[2]); const values_F = ready_rows.map(t => t[3]);
- 替换生成
new_table的代码,生成对应行数的索引序列进行遍历:
// 生成从0到row_count-1的索引数组,遍历每行生成内容 const new_table = Array.from({length: row_count}, (_, idx) => idx).map(x => make_row_from_col(this_table, x)).join('\n');
完整修改后代码
function Test() { const sSheet = SpreadsheetApp.getActiveSpreadsheet(); const srcSheet = sSheet.getSheetByName("Refinery"); const table = srcSheet.getRange("A:H").getValues(); // use "D2:M" if you have a header // 一次筛选出所有符合条件的行,避免重复遍历 const ready_rows = table.filter(t => t[7] == "READY TO SELL"); const row_count = ready_rows.length; const values_C = ready_rows.map(t => t[0]); const values_D = ready_rows.map(t => t[1]); const values_E = ready_rows.map(t => t[2]); const values_F = ready_rows.map(t => t[3]); Logger.log(values_C) Logger.log(values_D) Logger.log(values_E) Logger.log(values_F) Logger.log(values_C.length) const this_table = [values_C,values_D,values_E,values_F]; const make_row_from_col = (this_table, col) => this_table.map(x => x[col]).join("\t\t | \t\t"); // 遍历每行索引生成表格 const new_table = Array.from({length: row_count}, (_, idx) => idx).map(x => make_row_from_col(this_table, x)).join('\n'); Logger.log(new_table); }
内容的提问来源于stack exchange,提问作者TheFireFox
相关产品推荐
相关产品推荐

