首页 > 解决方案 > 带有 Excel 的 Powershell

问题描述

我需要做的是提取excel行中的数据并将它们输出到Excel上的不同行中。之后,我将需要使用提取的数据并对提取的数据执行某些条件。

这是我当前的脚本:

  1. 打开 excel 并应用公式
$excel = New-Object -ComObject excel.application
$filepath = 'D:\testexcel.xlsx'
$workbook = $excel.workbooks.open("$filepath")
$worksheet = $workbook.worksheets.item(1)

$excel.Visible = $true

$rows = $worksheet.range("A1").currentregion.rows.count 
$worksheet.range("S1:S$rows").formula = $worksheet.range("S1").formula 
  1. 查找行、应用公式并输出的函数
function test123(){
    param([string]$test123)

    $sourcefile = "D:\testexcel.xlsx"
    $sheetname = "abc"

    $excel = new-object -comobject excel.application
    $excel.Visible = $true
    $excelworkbook = $excel.Workbooks.open($sourcefile, 2, $true) 
    $excelworksheet = $excelworkbook.worksheets.item($sheetname)

    $row = 1
    $column = 1
    $found = $false
    while(($excelworksheet.cells.item($row, $column).value() -ne $null) -and($found -eq $false)){ 
        if(($excelworksheet.cells.item($row, $column).value()).toupper() -eq $test123.ToUpper()){
            write-host $excelworksheet.cells.item($row, $column).value() $excelworksheet.cells.item($row, $column+1).value(), 
            $excelworksheet.cells.item($row, $column +2).value() $found = $true
            }
        $row += 1
    }

    #close workbook
    $excelworkbook.close()
    $excel.quit()
}
test123 -test123 "Test123"

请指导我并告诉我这是否是正确的方法......谢谢

标签: excelpowershell

解决方案


请查看 Douge Finke 的 ImportExcel 模块。这个模块有能力做你需要的。

从 PowerShell 库中获取它:Install-Module -Name ImportExcel

Github 链接:https ://github.com/dfinke/ImportExcel

然后你可以做Get-Help Import-Excel -Examples这有很好的例子。


推荐阅读