簡體   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