繁体   English   中英

如何从Powershell中的目录解析单个Excel文件

[英]How to parse individual excel files from a directory in Powershell

我是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文件中提取名称,日期,描述,并将它们放入新的单独的工作表中。

感谢您的帮助,谢谢。

您通常处在正确的轨道上,只是您不应在循环主体中使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM