Read Excel data with Powershell and write to a variable

后端 未结 4 918
面向向阳花
面向向阳花 2020-12-14 13:01

Using PowerShell I would like to capture user input, compare the input to data in an Excel spreadsheet and write the data in corresponding cells to a variable. I am fairly n

4条回答
  •  爱一瞬间的悲伤
    2020-12-14 13:28

    User input can be read like this:

    $num = Read-Host "Store number"
    

    Excel can be handled like this:

    $xl = New-Object -COM "Excel.Application"
    $xl.Visible = $true
    $wb = $xl.Workbooks.Open("C:\path\to\your.xlsx")
    $ws = $wb.Sheets.Item(1)
    

    Looking up a value in one column and assigning the corresponding value from another column to a variable could be done like this:

    for ($i = 1; $i -le 3; $i++) {
      if ( $ws.Cells.Item($i, 1).Value -eq $num ) {
        $GoLiveDate = $ws.Cells.Item($i, 2).Value
        break
      }
    }
    

    Don't forget to clean up after you're done:

    $wb.Close()
    $xl.Quit()
    [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
    

提交回复
热议问题