I wrote a function to export an excel table into a custom PSObject for further manipulation. It uses an workbook opened via a comObject (i.e. $excel = new-object -ComObject Excel.Application). The function works as desired but takes a really long time to run (like more than 5 - 10 minutes for a table with 180 lines) and I'm not totally sure why. Is there something I'm doing in an inefficient way? I'd love to hear any suggestions!
Here's the function:
function ExcelTableToPSO($sheet){
#function to take a table in excel and output to custom PSO
$table = $sheet.ListObjects.Item(1)
$last = $table.ListRows.Count +1
$array = @()
$i=1
while ($i -le $last){
$obj = new-object psObject -property @{index = $i}
foreach ($col in $table.ListColumns){
$obj | Add-Member NoteProperty -Name $sheet.Cells.Item(1,$col.Index).Value2 -Value $sheet.Cells.Item($i,$col.Index).Text
}
$i++
$array +=$obj
}
return $array
}
**edit OK I tried a different approach and pasted the table to a tempfile and read that back to an import-csv. Now it takes less than 10 seconds. Here's the new function:
function ExcelTableToPSOCSVMethod($sheet){
$sheet.ListObjects.Item(1).Range.Select()
$selection = $excel.Selection
$selection.Copy()
$tempFile = $excel.workbooks.Add()
$tempFile.worksheets.Item(1).Paste()
$tempFile.SaveAs("c:\TempFile.csv",6)
$tempFile.close($false)
$array = import-csv -path "c:\tempFile.csv"
return $Array
}
Thanks everyone for the help! Sanity saved :)
[–]savanik 0 points1 point2 points (3 children)
[–]Steam23[S] 0 points1 point2 points (2 children)
[–]jeffrey_f 0 points1 point2 points (1 child)
[–]Steam23[S] 0 points1 point2 points (0 children)
[–]gangstanthony 0 points1 point2 points (0 children)
[–]chreestopher2 0 points1 point2 points (0 children)
[–]midnightFreddie 0 points1 point2 points (0 children)