简体   繁体   中英

How to parse individual excel files from a directory in Powershell

I am brand new to 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.

$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.

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.

Also, it is inefficient to create a new Excel instance in every loop iteration.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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