Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update a cell in a excel sheet using powershell

Tags:

powershell

I need to search for a word in a row from a spreadsheet and update another cell in the same row with a different value. For example, I have the data like this. I need to search for the person "Smith" from the below spreadsheet and update the value of the 'Status' column from 'Enabled' to 'Disabled' for that row.

"Region","Zone","Customer","Process","Status"
"TEST","East","Smith","HR","Disabled"
"TEST","East","Allen","Finance","Enabled"
"TEST","East","Jake","Payroll","Enabled"

I tried regex and few other functions before posting the question. But I can't get them to work.

Thanks.

like image 975
signalhouse Avatar asked Feb 19 '26 18:02

signalhouse


1 Answers

It's very easy to use Excel with PowerShell:

Add-Type -AssemblyName Microsoft.Office.Interop.Excel

$excelFile = 'C:\test\testsheet.xlsx' 

$searchFor            = 'Smith'

$excel                = New-Object -ComObject Excel.Application
$excel.Visible        = $true
$excel.ScreenUpdating = $true

$workbook  = $excel.Workbooks.Open( $excelFile ,$null, $false )

$ws        = $workbook.WorkSheets.item(1) 

[void]$ws.Activate()

$searchRange  = $ws.UsedRange

$searchResult = $searchRange.Find( $searchFor, [System.Type]::Missing, [System.Type]::Missing, 
                                               [Microsoft.Office.Interop.Excel.XlLookAt]::xlWhole, 
                                               [Microsoft.Office.Interop.Excel.XlSearchOrder]::xlByColumns, 
                                               [Microsoft.Office.Interop.Excel.XlSearchDirection]::xlNext )

while( $searchResult ) {

    $row = $searchResult.Row
    $col = $searchResult.Column

    $ws.Cells( $row, $col + 2 ).Value2 = 'Disabled'
    $searchResult = $searchRange.FindNext( $searchResult )

    if( $searchResult -and $searchResult.Row -le $row ) {
        break
    }
}

[void]$workbook.Save()
[void]$workbook.Close()
[void]$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
like image 114
f6a4 Avatar answered Feb 22 '26 15:02

f6a4



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!