【问题标题】:How to parse individual excel files from a directory in Powershell如何从Powershell中的目录解析单个excel文件
【发布时间】:2017-11-20 08:11:29
【问题描述】:

我是 Powershell 的新手。几个小时以来,我一直在努力完成一件看似简单的事情。非常感谢您的帮助。

我有一个巨大的文件夹和子文件夹列表,其中包含我想从中检索特定单元格数据的 Microsoft excel 文件 *.xlsm。

$Excel_files = (gci C:\Users\xxx\xxx\ -Recurse -File *.xlsm).FullName
foreach($getname in $Excel_files)
{
$Excel = New-Object -ComObject Excel.Application
$readbook = $Excel.WorkBooks.Open($Excel_files)
$readsheet = $readbook.WorkSheets.Item("SHEET NAME")
$Excel.Visible = $false
$getname = $readsheet.Cells.Item(8,3)
return $getname.text
}

我走对了吗?

这样做的目的是从几千个 *.xlsm 文件中提取名称、日期和描述,并将它们放入一个新的单独工作表中。

感谢任何帮助,谢谢。

【问题讨论】:

    标签: database excel powershell


    【解决方案1】:

    您通常走在正确的轨道上,但您不应该在循环体中使用return,因为这不仅会退出循环,还会完全退出封闭的函数/脚本。

    此外,在每次循环迭代中创建一个新的 Excel 实例也是低效的。

    代码的重构版本:

    # Determine the target workbooks' sheet name and cell address to extract.
    $targetSheet = 'SHEET NAME'
    $row = 8
    $col = 3
    
    # Create the Excel instance *once*.
    $xl = New-Object -ComObject Excel.Application
    
    # Loop over all workbooks of interest and extract the information of interest
    # and collect the values in array $cellVals
    # (There is no strict need for this intermediate step; omit `$cellValues = `
    #  to output the values directly.)
    $cellVals = Get-ChildItem C:\Users\xxx\xxx -File -Recurse -Filter *.xlsm | ForEach-Object {
      $wb = $xl.WorkBooks.Open($_.fullName)
      # Output the cell value of interest.
      $wb.WorkSheets($targetSheet).Cells($row, $col).text
      $wb.Close()
    }
    
    # Output the collected cell values.
    $cellVals
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      • 2013-12-07
      • 2017-08-01
      • 1970-01-01
      • 2021-09-08
      • 2023-02-09
      相关资源
      最近更新 更多