【问题标题】:select data from excel using powershell使用powershell从excel中选择数据
【发布时间】:2020-03-23 13:49:43
【问题描述】:

我正在编写一个脚本来使用 PowerShell v7.0 从.xlsx 文件中选择特定数据。

Excel 工作表包含以下数据:

+------------------------------+------------------+---------+
|           Company            |     Contact      | Country |
+------------------------------+------------------+---------+
| Alfreds Futterkiste          | Maria Anders     | x       |
| Centro comercial Moctezuma   | Francisco Chang  | x       |
| Ernst Handel                 | Roland Mendel    | x       |
| Island Trading               | Helen Bennett    | UK      |
| Laughing Bacchus Winecellars | Yoshi Tannamuri  | Canada  |
| Magazzini Alimentari Riuniti | Giovanni Rovelli | x       |
+------------------------------+------------------+---------+

要获得可以复制并粘贴到 Excel 工作表中的表格表示形式,请单击 Show code snippet,然后单击 Run code snippet

<table>
<thead>
    <tr>
        <th>Company</th>
        <th>Contact</th>
        <th>Country</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>Alfreds Futterkiste</td>
        <td>Maria Anders</td>
        <td>x</td>
    </tr>
    <tr>
        <td>Centro comercial Moctezuma</td>
        <td>Francisco Chang</td>
        <td>x</td>
    </tr>
    <tr>
        <td>Ernst Handel</td>
        <td>Roland Mendel</td>
        <td>x</td>
    </tr>
    <tr>
        <td>Island Trading</td>
        <td>Helen Bennett</td>
        <td>UK</td>
    </tr>
    <tr>
        <td>Laughing Bacchus Winecellars</td>
        <td>Yoshi Tannamuri</td>
        <td>Canada</td>
    </tr>
    <tr>
        <td>Magazzini Alimentari Riuniti</td>
        <td>Giovanni Rovelli</td>
        <td>x</td>
    </tr>
</tbody>
</table>

我做了什么:

$Output = [object][order]@{
                Name = $WorkSheet.Range("C1:C1000").Formula = "=x"
        }
        $Output

预期结果: Country = 'x' 的公司列表


Alfreds Futterkiste
Centro comercial 蒙特祖玛
恩斯特·亨德尔
Magazzini Alimentari Riuniti

谢谢!

【问题讨论】:

    标签: excel powershell


    【解决方案1】:

    您应该考虑使用专门的 PowerShell 模块与 Excel 工作簿交互 - 例如,ImportExcel

    如果这不是一个选项,您必须使用 Excel 的 COM 自动化接口,如您的问题所示:

    以下(易于调整)代码假定您的表位于 .xlsx 文件的第一个工作表中(并且该工作表不包含任何其他内容)。

    # Note: Be sure to specify a *full path*
    $xlFile = Convert-Path 'sample.xlsx'
    
    & {
    
     $xl = New-Object -ComObject Excel.Application
    
     $ws = $xl.Workbooks.Open($xlFile).Sheets.Item(1)
    
     $ws.UsedRange.Rows | 
       where { $_.Cells.Item(1, 3).Value2 -eq 'x' } |
         foreach { $_.Cells.Item(1, 1).Value2 }
    
     $xl.Quit()
    
    }
    

    注意显式的 .Item 方法调用,这仅在 PowerShell [Core] 6+ 中是必需的;在 Windows PowerShell 中,您可以更简洁地编写 $_.Cells(1, 3) 而不是 $_.Cells.Item(1, 3)

    有关背景信息,请参阅this GitHub issue

    【讨论】:

      猜你喜欢
      • 2021-01-12
      • 2011-05-30
      • 2016-12-04
      • 2013-04-29
      • 2015-12-07
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多