Create an Excel file using PowerShell script

Create an Excel file using PowerShell script 


Here is a code to write data into Excel file and save it in a particular path.

$excel = New-Object -ComObject excel.application

#$excel.visible = $True

$workbook = $excel.Workbooks.Add()

$SheetName = "MySheet"

$uregwksht= $workbook.Worksheets.Item(1)

$uregwksht.Name = $SheetName


$row = 1

$Column = 1

$uregwksht.Cells.Item($row,$column)= "Column Title"


for ($i = 2; $i -le 5; $i++)

{

    Write-Output $i

  $row = $row + 1

  $uregwksht.Cells.Item($row,$column)= "Abcd" + $i

}

$outputpath = "D:\test.xlsx"

$excel.displayalerts = $false

$workbook.Saveas($outputpath)

$excel.displayalerts = $true

Write-Output $("File saved on " + $outputpath )

$excel.Quit()


#ref - https://community.spiceworks.com/t/create-an-excel-file-from-within-powershell/1011485

#ref - https://chanmingman.wordpress.com/2022/10/02/powershell-write-to-excel-file/

No comments:

Post a Comment