Thursday, 18 March 2010

New-ExcelWorkbook.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script creates an Excel workbook using PowerShell 
  4. .DESCRIPTION 
  5.     This script demonstrates manipulating Excell with PowerShell 
  6.     and the Excel.Application COM object. 
  7. .NOTES 
  8.     File Name  : New-ExcelWorkbook.ps1 
  9.     Author     : Thomas Lee - tfl@psp.co.uk 
  10.     Requires   : PowerShell Version 2.0 
  11. .LINK 
  12.     This script posted to: 
  13.         http://pshscripts.blogspot.com/2010/03/new-excelworkbookps1.html
  14.     MSDN Sample posted at: 
  15.         http://msdn.microsoft.com/en-us/library/bb211359.aspx  
  16. .EXAMPLE
  17.     Run it and see one! 
  18. #> 
  19. ##  
  20. # Start of Script 
  21. ## 
  22. # Then we create and save a sample worksheet 
  23. # Create Excel object 
  24. $excel = new-object -comobject Excel.Application 
  25.     
  26. # Make Excel visible 
  27. $excel.visible = $true 
  28.    
  29. # Create a new workbook 
  30. $workbook = $excel.workbooks.add() 
  31.  
  32. # The default workbook has three sheets, remove 2 
  33. $S2 = $workbook.sheets | where {$_.name -eq "Sheet2"
  34. $s3 = $workbook.sheets | where {$_.name -eq "Sheet3"
  35. $s2.delete() 
  36. $s3.delete() 
  37. # Get sheet and update sheet name 
  38. $s1 = $workbook.sheets | where {$_.name -eq 'Sheet1'
  39. $s1.name = "PowerShell Sample" 
  40.    
  41. # Update workook properties 
  42. $workbook.author = "Thomas Lee - tfl@psp.co.uk" 
  43. $workbook.title = "Excel and PowerShell rock!" 
  44. $workbook.subject = "Demonstrating the Power of PowerShell with Excel" 
  45.    
  46. # Next update some cells in the worksheet 'PowerShell Sample' 
  47. $s1.range("A1:A1").cells="Cell a1" 
  48. $s1.range("A2:A2").cells="A2" 
  49. $s1.range("b1:b1").cells="Cell B1" 
  50. $s1.range("b2:b2").cells="b2" 
  51.  
  52. # now make a sum 
  53. $s1.range("E1:E2").cells="Widgets" 
  54. $s1.range("E2:E2").cells=2 
  55. $s1.range("E3:E3").cells=2 
  56. $s1.range("E4:E4").cells=38 
  57. $s1.range("D5:D5").cells="Total" 
  58. $s1.range("E5:E5").cells.formula = "=sum(e2,E4)" 
  59.    
  60. # And save it away: 
  61. $s1.saveas("c:\foo\xlsx3.xlsx"
  62. # end of script 

1 comment:

Me said...

When running the script like this, the excel instance stays open in the background. This could cause unwanted locks on the files opened.

Add the following at the end to cleanly close the instance:
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)


Source: http://technet.microsoft.com/en-us/library/ff730962.aspx