Skip to content

Commit

Permalink
Add concatenate-worksheets-into-one.osts
Browse files Browse the repository at this point in the history
  • Loading branch information
bastienperez committed Oct 23, 2024
1 parent 7245735 commit 1d33eed
Show file tree
Hide file tree
Showing 3 changed files with 90 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"version":"0.3.0","body":"// Script created by B.Perez 20241023\n\nfunction main(workbook: ExcelScript.Workbook) {\n // Get all worksheets in the workbook\n let sheets = workbook.getWorksheets();\n\n // Create a new worksheet for the combined data\n let newSheet = workbook.addWorksheet(\"CombinedData\");\n\n // Initialize a variable to track the current row for pasting data\n let currentRow = 0;\n\n // Get the header from the first sheet\n let firstSheet = sheets[0];\n let header = firstSheet.getUsedRange().getValues()[0];\n\n // Add the \"Source\" column header to the header array\n let updatedHeader = [...header, \"Source\"];\n\n // Set the header in the new sheet\n newSheet.getRangeByIndexes(currentRow, 0, 1, updatedHeader.length).setValues([updatedHeader]);\n\n // Move to the next row after the header\n currentRow++;\n\n // Loop through each sheet\n sheets.forEach((sheet, index) => {\n // Get the used range of the current sheet\n let usedRange = sheet.getUsedRange();\n\n // Skip the header row for all sheets\n let startRow = 1;\n\n // Get the data from the used range, excluding the header\n let data = usedRange.getValues().slice(startRow);\n\n // Add sheet name as the last column for each row\n let dataWithSheetName = data.map(row => {\n row.push(sheet.getName());\n return row;\n });\n\n // Paste the data into the new sheet starting at the current row\n newSheet.getRangeByIndexes(currentRow, 0, dataWithSheetName.length, dataWithSheetName[0].length).setValues(dataWithSheetName);\n\n // Update the current row for the next paste operation\n currentRow += dataWithSheetName.length;\n });\n\n // Auto-fit columns in the new sheet\n newSheet.getUsedRange().getFormat().autofitColumns();\n\n // Convert the used range to a table\n let lastUsedRange = newSheet.getUsedRange();\n let table = newSheet.addTable(lastUsedRange, true);\n table.setName(\"CombinedDataTable\");\n\n // Apply default table style (e.g., \"TableStyleMedium9\")\n table.setPredefinedTableStyle(\"TableStyleMedium2\");\n}","description":"","noCodeMetadata":"","parameterInfo":"{\"version\":1,\"originalParameterOrder\":[],\"parameterSchema\":{\"type\":\"object\",\"default\":{},\"x-ms-visibility\":\"internal\"},\"returnSchema\":{\"type\":\"object\",\"properties\":{}},\"signature\":{\"comment\":\"\",\"parameters\":[{\"name\":\"workbook\",\"comment\":\"\"}]}}","apiInfo":"{\"variant\":\"synchronous\",\"variantVersion\":2}"}
60 changes: 60 additions & 0 deletions concatenate-worksheets-into-one/concatenate-worksheets-into-one.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Script created by B.Perez 20241023

function main(workbook: ExcelScript.Workbook) {
// Get all worksheets in the workbook
let sheets = workbook.getWorksheets();

// Create a new worksheet for the combined data
let newSheet = workbook.addWorksheet("CombinedData");

// Initialize a variable to track the current row for pasting data
let currentRow = 0;

// Get the header from the first sheet
let firstSheet = sheets[0];
let header = firstSheet.getUsedRange().getValues()[0];

// Add the "Source" column header to the header array
let updatedHeader = [...header, "Source"];

// Set the header in the new sheet
newSheet.getRangeByIndexes(currentRow, 0, 1, updatedHeader.length).setValues([updatedHeader]);

// Move to the next row after the header
currentRow++;

// Loop through each sheet
sheets.forEach((sheet, index) => {
// Get the used range of the current sheet
let usedRange = sheet.getUsedRange();

// Skip the header row for all sheets
let startRow = 1;

// Get the data from the used range, excluding the header
let data = usedRange.getValues().slice(startRow);

// Add sheet name as the last column for each row
let dataWithSheetName = data.map(row => {
row.push(sheet.getName());
return row;
});

// Paste the data into the new sheet starting at the current row
newSheet.getRangeByIndexes(currentRow, 0, dataWithSheetName.length, dataWithSheetName[0].length).setValues(dataWithSheetName);

// Update the current row for the next paste operation
currentRow += dataWithSheetName.length;
});

// Auto-fit columns in the new sheet
newSheet.getUsedRange().getFormat().autofitColumns();

// Convert the used range to a table
let lastUsedRange = newSheet.getUsedRange();
let table = newSheet.addTable(lastUsedRange, true);
table.setName("CombinedDataTable");

// Apply default table style (e.g., "TableStyleMedium9")
table.setPredefinedTableStyle("TableStyleMedium2");
}
29 changes: 29 additions & 0 deletions concatenate-worksheets-into-one/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Concatenate All Worksheets into One

## Description

This script combines data from all worksheets in an Excel workbook into a new worksheet called `CombinedData`. It merges all data while avoiding duplicate headers and adds a new column that contains the name of the source worksheet for each row.

## Features

- **Sheet Consolidation**: Combines data from multiple worksheets into a single sheet.
- **Avoid Header Duplication**: Copies headers from only the first worksheet.
- **Source Column**: Adds a column named "source" to track the worksheet of origin for each row.
- **Efficient Data Processing**: Automatically excludes headers from subsequent sheets, ensuring clean data concatenation.

## Requirements

- **Uniform Headers**: All worksheets must have the same headers for the script to function correctly. Any mismatch in headers between sheets will cause the script to fail.

## Usage

1. Ensure all worksheets have identical headers.
2. Open your workbook in Excel.
3. Run the provided Office Script to generate a new worksheet with the concatenated data.
4. The "source" column will indicate the original sheet for each row.

### Example Execution

Here is an animated image showing the script in action:

![Script Execution](concatenate-worksheets-into-one.gif)

0 comments on commit 1d33eed

Please sign in to comment.