Files
ImportExcel/FAQ/How to Write to an Existing Excel File.md
2021-11-26 14:34:17 -08:00

1.3 KiB

Write to an Existing Excel File

Enumerate the Excel File

$ExcelPkgFile = Open-ExcelPackage -Path  "C:\Test\file.xlsx"

Contents of file.xlsx:
ExcelFileContents

Enumerate the Worksheet to View or Modify the Data

$WorkSheet = $ExcelPkgFile.Workbook.Worksheets["sheet1"].Cells #open excel worksheet cells from worksheet "sheet1"

Visual of Data Structure:
DataStructureExcelPkg

Modify a specific value by accessing row/col like a 2D Array:

$WorkSheet[1,4].Value = "New Column Header" #Starts at index 1 not 0

Contents of file.xlsx after modifying:
ExcelFileContentsPostAdd Can also load a value at a specific index:

$ValueAtIndex = $WorkSheet[2,1].Value #Loads the value at row 2, column A

$ValueAtIndex now contains: ValueAtIndexData

Save File After Modifying

The changes will not display in the Excel file until Close-ExcelPackage is called.

Close-ExcelPackage $ExcelPkgFile #close and save changes made to the Excel file.

Note: If the file is currently in use, Close-ExcelPackage will return an error and will not save the information.