Monday, October 11, 2010

Saving an Excel file using Powershell

I encountered a situation where I want to open an Excel sheet and write some information using Powershell commands and then close the file without my knowledge. I tried out several options and finally came up with the following code.

Before executing the script, you need to create an Excel file in root of the D drive with the name of “TestSave”. You may use any other location if so change the script accordingly.

$Exl = new-object -comobject Excel.Application
$Exl.visible=$false
$Exl.displayalerts=$False
$wb = $Exl.workbooks.Open("D:\TestSave.xlsx")
$ws = $wb.worksheets.item("Sheet1")
$ws.Cells.Item(1,3)='2009'
$wb.SaveAs("D:\TestSave.xlsx")
$Exl.Quit()

No comments:

Post a Comment