我已尽一切努力修改我的脚本,但仍然得到相同的结果,并且无法合并第 1 列中的所有数据。请参阅下面的脚本和屏幕截图。
// Merge cells in column 1 (PLATFORM)
var startRow = 2; // Start from the second row (after headers)
for (var i = 2; i <= selectedColumns.length + 1; i++) {
// Check if we are at the last row or the current platform is different from the next one
if (i === selectedColumns.length + 1 || selectedColumns[i - 1][0].trim().toLowerCase() !== selectedColumns[i - 2][0].trim().toLowerCase()) {
var numRowsToMerge = i - startRow; // Number of rows to merge
if (numRowsToMerge > 1) {
newWs.getRange(startRow, 1, numRowsToMerge, 1).merge(); // Merge the cells
}
startRow = i; // Move to the next group
}
}
这是我的完整脚本,我添加了注释以便您理解我的脚本。接下来我可以尝试什么?
function showInputBox() {
var ui = SpreadsheetApp.getUi();
var input = ui.prompt("Please enter your First Name and Last Name.", ui.ButtonSet.OK_CANCEL);
if (input.getSelectedButton() == ui.Button.OK) {
var userInput = input.getResponseText().trim();
if (!userInput) {
ui.alert("Please enter your First Name and Last Name");
return;
}
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getSheetByName("Monitoring (Database)");
var data = ws.getRange("A2:X" + ws.getLastRow()).getValues();
var userSelectedRep = userInput.toLowerCase();
var newData = data.filter(function (r) {
return r[23].toLowerCase() == userSelectedRep;
});
if (newData.length === 0) {
ui.alert("No data found for the entered name. Please check your input.");
return;
}
var selectedMonth;
var validMonthYear = false;
while (!validMonthYear) {
var monthInput = ui.prompt("Please enter the month and year (e.g., September 2024):", ui.ButtonSet.OK_CANCEL);
if (monthInput.getSelectedButton() == ui.Button.OK) {
var userInputMonthYear = monthInput.getResponseText().trim();
var dateParts = userInputMonthYear.split(' ');
// Validate input
if (dateParts.length === 2) {
selectedMonth = dateParts[0].toLowerCase();
var year = dateParts[1];
// Check if the month is valid
var monthIndex = new Date(Date.parse(selectedMonth + " 1, " + year)).getMonth();
if (monthIndex >= 0 && monthIndex < 12 && !isNaN(year)) {
validMonthYear = true; // Input is valid
} else {
ui.alert("Please enter a valid month and year (e.g., September 2024).");
}
} else {
ui.alert("Please enter both month and year.");
}
} else {
ui.alert("Month input canceled.");
return;
}
}
var filteredMonthData = newData.filter(function (r) {
var date = new Date(r[18]);
return date.toLocaleString('default', { month: 'long', year: 'numeric' }).toLowerCase() === selectedMonth + ' ' + year;
});
if (filteredMonthData.length > 0) {
var newWs = ss.insertSheet(userSelectedRep);
var headers = ["PLATFORM", "TOTAL TIME", "INSTITUTION", "QUANTITY/ACCESS CODE", "START DATE", "START TIME", "END DATE", "END TIME", "TYPE OF ACCESS"];
newWs.getRange(1, 1, 1, headers.length)
.setBackground("#a4c2f4")
.setFontWeight("bold")
.setFontSize(12)
.setWrap(true)
.setVerticalAlignment("middle")
.setHorizontalAlignment("center");
newWs.setRowHeight(1, 57);
var colWidths = [200, 100, 500, 106, 200, 114, 115, 130, 130];
for (var c = 1; c <= headers.length; c++) {
newWs.setColumnWidth(c, colWidths[c - 1]);
}
// Prepare the data for the new sheet
var selectedColumns = filteredMonthData.map(function (r) {
return [r[10], r[22], r[1], r[17], r[18], r[19], r[20], r[21], r[9]];
});
// Set values in the new sheet
newWs.getRange(2, 1, selectedColumns.length, selectedColumns[0].length).setValues(selectedColumns);
// Set the number format for START TIME and END TIME
newWs.getRange(2, 6, selectedColumns.length, 1).setNumberFormat("hh:mm"); // START TIME
newWs.getRange(2, 8, selectedColumns.length, 1).setNumberFormat("hh:mm"); // END TIME
// Merge cells in column 1 (PLATFORM)
var startRow = 2; // Start from the second row (after headers)
for (var i = 2; i <= selectedColumns.length + 1; i++) {
var currentPlatform = (i === selectedColumns.length + 1) ? "" : selectedColumns[i - 2][0].trim().toLowerCase(); // Adjusted index
var previousPlatform = (i - 1 === 1) ? "" : selectedColumns[i - 3][0].trim().toLowerCase(); // Adjusted index
if (currentPlatform !== previousPlatform) {
var numRowsToMerge = i - startRow; // Number of rows to merge
if (numRowsToMerge > 1) {
newWs.getRange(startRow, 1, numRowsToMerge, 1).merge(); // Merge the cells
}
startRow = i; // Move to the next group
}
}
// Align all data in the new sheet
newWs.getRange(2, 1, selectedColumns.length, headers.length)
.setHorizontalAlignment("left")
.setVerticalAlignment("middle");
// Set headers at the top
newWs.getRange(1, 1, 1, headers.length).setValues([headers]);
// Define chart range
var chartRange = newWs.getRange(2, 1, selectedColumns.length, 2);
// Create the chart
var chart = newWs.newChart()
.setChartType(Charts.ChartType.COLUMN) // Set the chart type
.addRange(chartRange) // Add the data range
.setPosition(2, 11, 0, 0) // Position of the chart (row, column, offsetX, offsetY)
.setOption('title', 'Institution Access Data for ' + selectedMonth + ' ' + year)
.setOption('titleTextStyle', {
color: '#333333',
fontSize: 18,
bold: true
})
.setOption('vAxis.title', 'Total Time')
.setOption('vAxis.titleTextStyle', {
italic: true,
color: '#666666',
fontSize: 14
})
.setOption('hAxis.title', 'Platform')
.setOption('hAxis.titleTextStyle', {
italic: true,
color: '#666666',
fontSize: 14
})
.setOption('legend', { position: 'top', alignment: 'center' })
.setOption('backgroundColor', '#f9f9f9')
.setOption('colors', ['#4CAF50', '#2196F3']) // Customize colors
.setOption('is3D', true) // Optional: make the chart 3D
.setOption('width', 800) // Set a wider chart
.setOption('height', 400) // Set a taller chart
.setOption('hAxis.slantedText', true) // Rotate x-axis labels
.setOption('hAxis.slantedTextAngle', 45) // Angle of rotation
.setOption('dataLabel', true) // Show data labels
.build();
newWs.insertChart(chart);
} else {
ui.alert("No matching data found for the entered month.");
}
} else {
ui.alert("Operation Canceled.");
}
}
我已经测试了上面提供的代码,我注意到第一个片段与完成的脚本有些不同,我认为您已经部分解决了一些问题。测试完成的脚本后,产生的问题位于最后合并行内,并且根据我如何解释当前问题,以下是我将如何执行此操作。
修改后的代码:
var startRow = 2;
var lastRow = newWs.getLastRow();
for (var i = startRow; i <= lastRow; i++) {
var currentPlatform = (i < 1) ? "" : selectedColumns[i - 2][0].trim().toLowerCase();
var previousPlatform = (i - 1 === 1) ? "" : selectedColumns[i - 3][0].trim().toLowerCase(); // Adjusted index
if (currentPlatform !== previousPlatform) {
var numRowsToMerge = i - startRow;
if (numRowsToMerge > 1) {
newWs.getRange(startRow, 1, numRowsToMerge, 1).merge();
}
startRow = i;
}
}
if (startRow < lastRow) {
newWs.getRange(startRow, 1, lastRow - startRow + 1, 1).merge();
}
完成代码:
function showInputBox() {
var ui = SpreadsheetApp.getUi();
var input = ui.prompt("Please enter your First Name and Last Name.", ui.ButtonSet.OK_CANCEL);
if (input.getSelectedButton() == ui.Button.OK) {
var userInput = input.getResponseText().trim();
if (!userInput) {
ui.alert("Please enter your First Name and Last Name");
return;
}
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getSheetByName("Monitoring (Database)");
var data = ws.getRange("A2:X" + ws.getLastRow()).getValues();
var userSelectedRep = userInput.toLowerCase();
var newData = data.filter(function (r) {
return r[23].toLowerCase() == userSelectedRep;
});
if (newData.length === 0) {
ui.alert("No data found for the entered name. Please check your input.");
return;
}
var selectedMonth;
var validMonthYear = false;
while (!validMonthYear) {
var monthInput = ui.prompt("Please enter the month and year (e.g., September 2024):", ui.ButtonSet.OK_CANCEL);
if (monthInput.getSelectedButton() == ui.Button.OK) {
var userInputMonthYear = monthInput.getResponseText().trim();
var dateParts = userInputMonthYear.split(' ');
// Validate input
if (dateParts.length === 2) {
selectedMonth = dateParts[0].toLowerCase();
var year = dateParts[1];
// Check if the month is valid
var monthIndex = new Date(Date.parse(selectedMonth + " 1, " + year)).getMonth();
if (monthIndex >= 0 && monthIndex < 12 && !isNaN(year)) {
validMonthYear = true; // Input is valid
} else {
ui.alert("Please enter a valid month and year (e.g., September 2024).");
}
} else {
ui.alert("Please enter both month and year.");
}
} else {
ui.alert("Month input canceled.");
return;
}
}
var filteredMonthData = newData.filter(function (r) {
var date = new Date(r[18]);
return date.toLocaleString('default', { month: 'long', year: 'numeric' }).toLowerCase() === selectedMonth + ' ' + year;
});
if (filteredMonthData.length > 0) {
var newWs = ss.insertSheet(userSelectedRep);
var headers = ["PLATFORM", "TOTAL TIME", "INSTITUTION", "QUANTITY/ACCESS CODE", "START DATE", "START TIME", "END DATE", "END TIME", "TYPE OF ACCESS"];
newWs.getRange(1, 1, 1, headers.length)
.setBackground("#a4c2f4")
.setFontWeight("bold")
.setFontSize(12)
.setWrap(true)
.setVerticalAlignment("middle")
.setHorizontalAlignment("center");
newWs.setRowHeight(1, 57);
var colWidths = [200, 100, 500, 106, 200, 114, 115, 130, 130];
for (var c = 1; c <= headers.length; c++) {
newWs.setColumnWidth(c, colWidths[c - 1]);
}
// Prepare the data for the new sheet
var selectedColumns = filteredMonthData.map(function (r) {
return [r[10], r[22], r[1], r[17], r[18], r[19], r[20], r[21], r[9]];
});
// Set values in the new sheet
newWs.getRange(2, 1, selectedColumns.length, selectedColumns[0].length).setValues(selectedColumns);
// Set the number format for START TIME and END TIME
newWs.getRange(2, 6, selectedColumns.length, 1).setNumberFormat("hh:mm"); // START TIME
newWs.getRange(2, 8, selectedColumns.length, 1).setNumberFormat("hh:mm"); // END TIME
var startRow = 2;
var lastRow = newWs.getLastRow();
for (var i = startRow; i <= lastRow; i++) {
var currentPlatform = (i < 2) ? "" : selectedColumns[i - 2][0].trim().toLowerCase();
var previousPlatform = (i - 1 === 1) ? "" : selectedColumns[i - 3][0].trim().toLowerCase(); // Adjusted index
if (currentPlatform !== previousPlatform) {
var numRowsToMerge = i - startRow;
if (numRowsToMerge > 1) {
newWs.getRange(startRow, 1, numRowsToMerge, 1).merge();
}
startRow = i;
}
}
if (startRow < lastRow) {
newWs.getRange(startRow, 1, lastRow - startRow + 1, 1).merge();
}
// Align all data in the new sheet
newWs.getRange(2, 1, selectedColumns.length, headers.length)
.setHorizontalAlignment("left")
.setVerticalAlignment("middle");
// Set headers at the top
newWs.getRange(1, 1, 1, headers.length).setValues([headers]);
// Define chart range
var chartRange = newWs.getRange(2, 1, selectedColumns.length, 2);
// Create the chart
var chart = newWs.newChart()
.setChartType(Charts.ChartType.COLUMN) // Set the chart type
.addRange(chartRange) // Add the data range
.setPosition(2, 11, 0, 0) // Position of the chart (row, column, offsetX, offsetY)
.setOption('title', 'Institution Access Data for ' + selectedMonth + ' ' + year)
.setOption('titleTextStyle', {
color: '#333333',
fontSize: 18,
bold: true
})
.setOption('vAxis.title', 'Total Time')
.setOption('vAxis.titleTextStyle', {
italic: true,
color: '#666666',
fontSize: 14
})
.setOption('hAxis.title', 'Platform')
.setOption('hAxis.titleTextStyle', {
italic: true,
color: '#666666',
fontSize: 14
})
.setOption('legend', { position: 'top', alignment: 'center' })
.setOption('backgroundColor', '#f9f9f9')
.setOption('colors', ['#4CAF50', '#2196F3']) // Customize colors
.setOption('is3D', true) // Optional: make the chart 3D
.setOption('width', 800) // Set a wider chart
.setOption('height', 400) // Set a taller chart
.setOption('hAxis.slantedText', true) // Rotate x-axis labels
.setOption('hAxis.slantedTextAngle', 45) // Angle of rotation
.setOption('dataLabel', true) // Show data labels
.build();
newWs.insertChart(chart);
} else {
ui.alert("No matching data found for the entered month.");
}
} else {
ui.alert("Operation Canceled.");
}
}
示例输出:
参考: