tedeansiii

Working with Excel COM in PowerShell

Jun 4th, 2022 (edited)
625
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Path to CSV
  2. $CSV = "C:\some folder\CSV.csv"
  3. # Path to Report blank file
  4. $Report = "C:\some folder\Report.xls" # May work with xlsx but havent tried
  5. # Add Items to CSV
  6. Add-Content $CSV $VariableList
  7. Add-Content $CSV $VariableList1
  8. Add-Content $CSV $VariableList2
  9. Add-Content $CSV $VariableList3
  10. Add-Content $CSV $VariableList4
  11. Add-Content $CSV $VariableList5
  12.  
  13. ## Work with Excell
  14. # Copy Data from CSV
  15. ## Open CSV and copy to clipboard
  16. $Excel = New-Object -ComObject excel.application
  17. $Excel.visible = $false
  18. $Workbook = $excel.Workbooks.open($CSV)
  19. $Worksheet = $Workbook.WorkSheets.item(“Sheet1”)
  20. $worksheet.activate()  
  21. $range = $WorkSheet.Range(“A2:C32”)
  22. $range.Copy() | out-null
  23. $Excel.Quit()
  24. Remove-Variable -Name excel
  25. [gc]::collect()
  26. [gc]::WaitForPendingFinalizers()
  27.  
  28. ## Open tonight's report and past clipboard data
  29. $Excel = New-Object -ComObject excel.application
  30. $Excel.visible = $false
  31. $Workbook = $excel.Workbooks.open($Report)
  32. $Worksheet = $Workbook.WorkSheets.item(“Night Report”)
  33. $worksheet.activate()
  34. $Range = $Worksheet.Range(“A1”)
  35. $Worksheet.Paste($Range)
  36. $workbook.Save()  
  37. $Excel.Quit()
  38. Remove-Variable -Name excel
  39. [gc]::collect()
  40. [gc]::WaitForPendingFinalizers()
  41.  
  42. # Some notes: Add-Content if i remeber correctly just adds to the previous underneath, once you are done concatting variables you need to know the range for pasting ie 6 add-contents might equal 45 rows of data in the variable, when pasting into the xls you would specify the range of A1:A45. if you dont or wont know this you can do a $CSV.count and for range specify A1:$($CSV.count, OR do a longer than needed range ie A1LA1200 but I dont remember if that gives error or not). Also note that above I have ommitted other code blocks of the same info, youll notice my copy does A2:C42, my CSV was exported from NetApp with other Data, so you can copy more than one single row but in the example above im doing 1 row, I left my range to clue you in that more can be done, change as necessary
  43.  
Add Comment
Please, Sign In to add comment