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

时间:2017-11-19 01:51:57

标签: database excel 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文件中提取名称,日期,描述并将它们放入一个新的单独表格中。

感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

你通常在正确的轨道上,除非你不应该在你的循环体中使用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