我在电子表格中有一个行号列表,我需要更改其背景颜色。由于电子表格非常大(10+张,每张近 5000 行),我正在尝试构建一个范围,以便我可以批量设置背景,因为单独处理每一行最多需要 6 分钟的时间。
这是我的代码:
// highlight required rows
var first = -1, last = -1;
for(var j = 0; j < rowNumsToHighlight.length; j++) {
if(first == -1) {
first = rowNumsToHighlight[j];
continue;
}
// if the current row number is one more than the previous, update last to be the current row number
if(rowNumsToHighlight[j] - 1 == rowNumsToHighlight[j - 1]) {
last = rowNumsToHighlight[j];
continue;
}
// otherwise the last row should be the previous one
else {
last = rowNumsToHighlight[j - 1];
}
var numRows = (last - first) + 1;
var range = sheet.getRange(first, 1, numRows, 4);
if(range.getBackground().toUpperCase() != highlightColour.toUpperCase()) {
range.setBackground(highlightColour);
}
first = -1;
last = -1;
}
rowNumsToHighlight
只是一个数组,如下所示:[205,270,271,272,278,279]
。因此,以此为例,setBackground
应在第 205 行、第 270-272 行和第 278-279 行运行。
我相当确定解决方案很简单,但只是看不到它。感谢您的帮助。
====更新代码====
根据下面的 Serge 代码,我通过减少 getRange()
调用次数再次提高了效率。时间从 78 秒缩短到 54 秒。
function updateColours(sheet, array, colour){
var columns = sheet.getLastColumn();
var rows = sheet.getLastRow();
var range = sheet.getRange(1, 1, rows, columns);
Logger.log("Resetting highlight on all rows...");
range.setBackground(null);
var backgrounds = range.getBackgrounds();
for(var n = 0; n < backgrounds.length; n++){
var rowIdx = n + 1;
if(array.indexOf(rowIdx) > -1){
for(var c = 0; c < columns; c++){
backgrounds[n][c] = colour;
}
}
}
Logger.log("Highlighting non-translated rows...");
range.setBackgrounds(backgrounds);
}
最佳答案
也许这个更快(?)并且以一种使您的工作更轻松的方式构建(带参数的函数)。
它只向工作表写入一次(如果您在写入之前清除颜色,则写入 2 次)...
使用如下:
function testBG(){
updateColors(0,[7,8,9,18,19,23]);
}
function updateColors(sheetNum,array){
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheets()[sheetNum];
var columns = sh.getMaxColumns();
var range = sh.getRange(1,1,sh.getMaxRows(),columns);
sh.getRange(1,1,sh.getMaxRows(),columns).setBackground(null);// use this if you want to clear all colors before setting them
var backGrounds = range.getBackgrounds();// get all cells BG
for(var n=0;n<backGrounds.length;n++){
var rowIdx = n+1;
if(array.indexOf(rowIdx)>-1){
for(c=0;c<columns;c++){
backGrounds[n][c]="#F00";// if row number is in the array fill in red
}
}
}
sh.getRange(1,1,sh.getMaxRows(),columns).setBackgrounds(backGrounds);//update sheet in one call
}
test sheet in view only ,复制一份进行测试。
关于google-apps-script - 应用脚本 : Construct range of rows from array of row numbers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31164465/