src/Excel/Read-XrmExcelSheet.ps1
|
<# .SYNOPSIS Read Excel Sheet. .DESCRIPTION Read a worksheet and return a collection of objects using the header row as property names. Use -AsArray to keep the legacy raw Excel array behavior. Requires Windows and Microsoft Excel (COM automation). .PARAMETER ExcelFilePath Full path to Excel file. A relative path is read from the PowerShell location. .PARAMETER SheetName Excel sheet name. .PARAMETER HeaderRowIndex Row number of the sheet that contains the column headers (row 3 when the table starts at A3). Default: the first row that holds a value. .PARAMETER AsArray Return the raw Excel value array instead of PSCustomObject rows. .OUTPUTS PSCustomObject. One object per non-empty row below the header row, with one property per column header (an empty header gives ColumnN, a repeated one gets a number suffix). With AsArray: System.Object[,], the raw values of the used range (1-based indexes; a single value for a one-cell range). .EXAMPLE $rows = Read-XrmExcelSheet -ExcelFilePath "C:\Temp\Accounts.xlsx" -SheetName "Accounts"; foreach ($row in $rows) { $account = New-XrmEntity -LogicalName "account" -Attributes @{ "name" = $row.Name }; Add-XrmRecord -XrmClient $xrmClient -Record $account | Out-Null; } .LINK https://github.com/AymericM78/PowerDataOps/blob/main/documentation/commands/Read-XrmExcelSheet.md #> function Read-XrmExcelSheet { [CmdletBinding()] [OutputType([PSCustomObject[]])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [ValidateScript({ Test-Path $_ })] [String] $ExcelFilePath, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [String] $SheetName, [Parameter(Mandatory = $false)] [ValidateRange(1, [int]::MaxValue)] [int] $HeaderRowIndex = 1, [Parameter(Mandatory = $false)] [switch] $AsArray = $false ) begin { $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); } process { Assert-XrmWindowsInternal -Feature "Excel automation (COM)"; # Relative to the PowerShell location, not to the folder of the process (M25) if ($ExcelFilePath) { $ExcelFilePath = Resolve-XrmPathInternal -Path $ExcelFilePath; } $workbook = $null; $sheet = $null; $sheetContentRange = $null; $excelApplication = New-Object -ComObject Excel.Application; try { $excelApplication.Visible = $false; $excelApplication.ScreenUpdating = $false; # $false, not 'False': a non-empty string is $true for COM (M33) $excelApplication.DisplayAlerts = $false; $workbook = $excelApplication.Workbooks.Open($ExcelFilePath); $sheet = $workbook.Sheets | Where-Object -Property Name -EQ -Value $SheetName | Select-Object -First 1; if ($null -eq $sheet) { throw "Excel sheet '$SheetName' was not found in '$ExcelFilePath'."; } $sheetContentRange = $sheet.UsedRange; $sheetValuesArray = $sheetContentRange.Value2; if ($AsArray) { return , $sheetValuesArray; } $rowCount = [int]$sheetContentRange.Rows.Count; $columnCount = [int]$sheetContentRange.Columns.Count; # HeaderRowIndex is the row number of the sheet: the used range starts at its first non-empty row, which was read as row 1 (M32). # Without HeaderRowIndex, the header is still the first used row, wherever it is. $firstRow = [int]$sheetContentRange.Row; $headerIndex = 1; if ($PSBoundParameters.ContainsKey("HeaderRowIndex")) { $headerIndex = $HeaderRowIndex - $firstRow + 1; } if ($headerIndex -lt 1 -or $headerIndex -gt $rowCount) { throw "Excel sheet '$SheetName' does not contain header row $HeaderRowIndex (its cells are used from row $firstRow to row $($firstRow + $rowCount - 1))."; } if ($null -eq $sheetValuesArray) { return @(); } $headerNames = @(); $headerNamesCount = @{}; for ($columnIndex = 1; $columnIndex -le $columnCount; $columnIndex++) { if ($sheetValuesArray -is [System.Array]) { $headerValue = $sheetValuesArray[$headerIndex, $columnIndex]; } else { $headerValue = $sheetValuesArray; } $headerName = [string]$headerValue; if ([string]::IsNullOrWhiteSpace($headerName)) { $headerName = "Column$columnIndex"; } if ($headerNamesCount.ContainsKey($headerName)) { $headerNamesCount[$headerName]++; $headerName = "$headerName$($headerNamesCount[$headerName])"; } else { $headerNamesCount[$headerName] = 1; } $headerNames += $headerName; } $rows = @(); for ($rowIndex = ($headerIndex + 1); $rowIndex -le $rowCount; $rowIndex++) { $row = [ordered]@{}; $hasValue = $false; for ($columnIndex = 1; $columnIndex -le $columnCount; $columnIndex++) { $cellValue = $sheetValuesArray[$rowIndex, $columnIndex]; if ($null -ne $cellValue -and -not [string]::IsNullOrWhiteSpace([string]$cellValue)) { $hasValue = $true; } $row[$headerNames[$columnIndex - 1]] = $cellValue; } if ($hasValue) { $rows += [PSCustomObject]$row; } } return $rows; } finally { if ($null -ne $workbook) { try { $workbook.Close($false); } catch { Write-Verbose "Workbook not closed: $($_.Exception.Message)"; } } # EXCEL.EXE stayed in memory after each call (M33) Stop-XrmExcelApplicationInternal -Application $excelApplication -ComObjects @($sheetContentRange, $sheet, $workbook); } } end { $StopWatch.Stop(); Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch; } } Export-ModuleMember -Function Read-XrmExcelSheet -Alias *; |