How can I update an existing Excel file with multiple sheets using PowerShell.
I'm using the below code for an Excel file with a single sheet, but need to do something similar to an Excel file with multiple sheets (Sheet names are known).
So I need to import all existing sheets, update each sheet individually and then save all changed sheets to a new multi-sheet Excel file.
Import-Module activedirectory
# Read existing Excel file
$xlsx = import-excel 'D:\users.xlsx'
# Get the properties
$Properties = [Collections.Generic.List[Object]]$xlsx[0].psobject.properties.Name
# Add new columns. Position 6 & 7
$Properties.Insert(6, "Name")
$Properties.Insert(7, "Team")
# Obtain name and team from AD for every user (ID)
foreach ($row in $xlsx)
{
$user = Get-AD -CN $row.ID
$row | Add-Member -Name 'Name' -Value $user[0] -MemberType NoteProperty
$row | Add-Member -Name 'Team' -Value $user[1] -MemberType NoteProperty
}
# Create a new Excel file
$xl = $xlsx | Select-Object -Property $Properties | Export-Excel 'D\new_users.xlsx' -Append -WorksheetName "USERS"
$Sheet = $xl.Workbook.Worksheets["USERS"]
Close-ExcelPackage $xl –Show
Any help much approciated!
You can iterate over each spreadsheet with
Get-ExcelSheetInfothen useImport-Excelwith the-WorksheetNameparameter. If you want to append new columns to each spreadsheet then something like this should work:Adding a simple example appending columns to an Excel file with 2 Spreadsheets.
First we create a test
test.xlsxfile with theIdof the first 4 processes onProcessesSpreadsheet and theNameof the first 4 services onServicesSpreadsheet:Looking, at the current file:
Now, for the
ProcessesSpreadsheet append columns Id, ProcessName and HandleCount in that order and for theServicesSpreadsheet append columns Status, Name and DisplayName.Lastly, check how the result looks like: