简体   繁体   English

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

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

I am brand new to powershell. 我是Powershell的新手。 I've been trying to accomplish one seemly simple thing for hours. 我一直在努力完成一件看似简单的事情,数小时之久。 I'd really appreciate some help. 我真的很感谢您的帮助。

I have a gigantic list of folders and sub-folders full of Microsoft excel files *.xlsm that I would like to retrieve specific cell data from. 我有一个巨大的文件夹和子文件夹列表,里面充满了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
}

Am I on the right track? 我在正确的轨道上吗?

The intent of this is to pull the name, date, description from a couple thousand *.xlsm files and put them into a new separate sheet. 这样做的目的是从成千上万个* .xlsm文件中提取名称,日期,描述,并将它们放入新的单独的工作表中。

I appreciate any help, thanks. 感谢您的帮助,谢谢。

You're generally on the right track, except you shouldn't use return in your loop body, as that will not only exit the loop but the enclosing function / script altogether. 您通常处在正确的轨道上,只是您不应在循环主体中使用return ,因为这不仅会退出循环,而且会完全封闭函数/脚本。

Also, it is inefficient to create a new Excel instance in every loop iteration. 而且,在每次循环迭代中创建新的Excel实例效率低下。

A refactored version of your code: 您的代码的重构版本:

# 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