每个月末,我都会复制一个包含多个隐藏行的选项卡,然后从重复选项卡中删除所有这些隐藏行。为此,我修改了以下Tanaike的代码,代码运行没有任何错误,但所有隐藏行仍然存在。
请建议对代码进行哪些修改。
这是修改后的代码:
function deleteHiddenRows() {
const spreadsheetId = SpreadsheetApp.openById(gid);
const sheetName = spreadsheetId.getSheetByName(tab);
const lastRow = sheetName.getLastRow();
const sheetId = sheetName.getSheetId();
const fields = "sheets(data(rowMetadata(hiddenByUser)),properties/sheetId)";
const rowMetadata = SheetsV4.Spreadsheets.get(gid, { fields: fields }).sheets[0].data[0].rowMetadata;
const requests = rowMetadata.reduce((ar, { hiddenByUser }, i) => {
if (hiddenByUser && i > 0 && i + 1 < lastRow) ar.push({ deleteDimension: { range: { sheetId, startIndex: i, endIndex: i + 1, dimension: "ROWS" } } });
return ar;
}, []);
SheetsV4.Spreadsheets.batchUpdate({requests}, gid);
}
我已经尝试过你的代码并做了一些小的更改,这对我来说是有效的。看来问题来自于Reduce Array Method 的行为,我改变了它。 这是更新后的代码。
function deleteHiddenRows() {
const spreadsheetId = 'Replace it with your actual SpreadsheetID';
const sheetName = 'Replace it with your duplicate sheet tab';
const spreadsheet = SpreadsheetApp.openById(spreadsheetId);
const sheet = spreadsheet.getSheetByName(sheetName);
const sheetId = sheet.getSheetId();
const lastRow = sheet.getLastRow();
const fields = "sheets(data(rowMetadata(hiddenByUser)),properties/sheetId)";
// Fetch row metadata using Sheets API v4
const rowMetadataResponse = Sheets.Spreadsheets.get(spreadsheetId, { fields: fields }); //For some reason SheetsV4.Spreadsheets.get doesnt work in my end.
const rowMetadata = rowMetadataResponse.sheets[0].data[0].rowMetadata;
// Build batch update requests to delete hidden rows
const requests = [];
for (let i = rowMetadata.length - 1; i >= 0; i--) {
if (rowMetadata[i].hiddenByUser) {
requests.push({ deleteDimension: { range: { sheetId: sheetId, startIndex: i, endIndex: i + 1, dimension: 'ROWS' } } });
}
}
Sheets.Spreadsheets.batchUpdate({ requests: requests }, spreadsheetId);
}
而不是使用这部分代码
const requests = rowMetadata.reduce((ar, { hiddenByUser }, i) => {
if (hiddenByUser && i > 0 && i + 1 < lastRow) ar.push({ deleteDimension: { range: { sheetId, startIndex: i, endIndex: i + 1, dimension: "ROWS" } } });
return ar;
}, []);
尝试使用这个:
const requests = [];
for (let i = rowMetadata.length - 1; i >= 0; i--) {
if (rowMetadata[i].hiddenByUser) {
requests.push({ deleteDimension: { range: { sheetId: sheetId, startIndex: i, endIndex: i + 1, dimension: 'ROWS' } } });
}
}
我使用
for
循环对数据范围的 rowMetadata
进行迭代。这种反向迭代可以防止出现问题,并确保删除行不会影响尚未处理的行的索引。