function main(workbook: ExcelScript.Workbook) {
const templateName = 'TemplateDoNotDelete';
const template = workbook.getWorksheet(templateName);
if (!template) {
throw new Error(`Template sheet was not found.`);
}
// Get current date in Pacific Time
const pacificDate = new Date(
new Date().toLocaleString("en-US", { timeZone: "America/Los_Angeles" })
);
const day = pacificDate.getDate().toString().padStart(2, '0');
const month = (pacificDate.getMonth() + 1).toString().padStart(2, '0');
const year = pacificDate.getFullYear().toString();
const newSheetName = `${day}.${month}.${year}`;
// Delete existing sheet with same name, if found
const existingSheet = workbook.getWorksheet(newSheetName);
if (existingSheet) {
existingSheet.delete();
}
// Copy template
const copiedSheet = template.copy(
ExcelScript.WorksheetPositionType.after,
template
);
// Rename copied sheet
copiedSheet.setName(newSheetName);
// Get tables from new sheet
const tables = copiedSheet.getTables();
const tableNames = tables.map(t => t.getName());
// ⭐ NEW CODE ADDED BELOW ⭐
// Reapply sort settings from template to copied tables
const templateTables = template.getTables();
templateTables.forEach((templateTable, index) => {
const copiedTable = tables[index];
if (copiedTable && templateTable) {
const templateSort = templateTable.getSort();
const copiedSort = copiedTable.getSort();
// Copy sort fields from template
const sortFields = templateSort.getFields();
if (sortFields.length > 0) {
copiedSort.apply(sortFields);
}
}
});
// ⭐ NEW CODE ADDED ABOVE ⭐
return {
worksheetName: copiedSheet.getName(),
tableNames: tableNames
};
}