从Excel工作表中读取值

时间:2017-12-05 07:27:20

标签: excel-vba powershell vba excel

enter image description here

$filepath = "C:\Users\Desktop\New folder\Tangent.xlsx"
$sheetname = "sheet"
$objExcel = New-Object -ComObject Excel.Application
$objExcel.Visible = $false
$WorkBook = $objExcel.Workbooks.Open($filepath)
$WorkBook.sheets | Select-Object -Property Name
$WorkSheet = $WorkBook.Sheets.Item($sheetname)
$myObj = [PSCustomObject][ordered]@{
    john  = $WorkSheet.Range("B1").Text
    Rebel = $WorkSheet.Range("B2").Text
    MArk  = $WorkSheet.Range("B3").Text
    Susan = $WorkSheet.Range("B4").Text
    Patty = $WorkSheet.Range("B5").Text
}

我已经将所有名称硬编码到代码中,这是一种奇怪的方式。我希望它从Excel directing using命令中读取。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

创建一个空的哈希表,并在迭代Excel工作表中的行时填充它,然后创建对象。

$ht = @{}
$i = 1
while ($WorkSheet.Cells.Item($i, 1).Text) {
    $ht[$WorkSheet.Cells.Item($i, 1).Text] = $WorkSheet.Cells.Item($i, 2).Text
    $i++
}
$obj = [PSCustomObject]$ht

未经测试,因为我手头没有Excel。