On his blog Accelerating Excel File Reading in PowerShell Robert M. Tups Jr. explains that when you load into PowerShell quickly, actually scanning Excel cells is very slow. On the other hand, PowerShell can quickly read a text file, so its solution is to load the spreadsheet into PowerShell, use the native CSV export process for Excel to save it as a CSV file, and then use the standard Import-Csv PowerShells cmdlet to process data incredibly fast . He reports that this enabled him to import the process 20 times faster!
Using the Toups code, I created an Import-Excel function that allows you to easily import spreadsheet data. My code adds the ability to select a specific worksheet in an Excel workbook, and not just use the default worksheet (i.e. the active worksheet when saving the file). If you omit the โSheetName parameter, it uses the default table.
function Import-Excel([string]$FilePath, [string]$SheetName = "") { $csvFile = Join-Path $env:temp ("{0}.csv" -f (Get-Item -path $FilePath).BaseName) if (Test-Path -path $csvFile) { Remove-Item -path $csvFile }
These additional features are used by Import-Excel:
function FindSheet([Object]$workbook, [string]$name) { $sheetNumber = 0 for ($i=1; $i -le $workbook.Sheets.Count; $i++) { if ($name -eq $workbook.Sheets.Item($i).Name) { $sheetNumber = $i; break } } return $sheetNumber } function SetActiveSheet([Object]$workbook, [string]$name) { if (!$name) { return } $sheetNumber = FindSheet $workbook $name if ($sheetNumber -gt 0) { $workbook.Worksheets.Item($sheetNumber).Activate() } return ($sheetNumber -gt 0) }
Michael sorens
source share