如何使用PowerShell来复制几个Excel工作表,并创build一个新的?

我有大约70个excel文件,我想合并成一个文件。 每份文件只有一张表格,并遵循以下格式:

  • 行A与标题列AF
  • B行与第一个条目
  • C行与第二项
  • 在一些床单上最多有150行

我想从每列的AF栏中刮取信息,并将其与来自同一目录中的所有其他文件的信息组合成新文件。

注意:我只想捕获列AF,因为在列G中存在一个是,否数据集来pipe理列F中的下拉列表。

我尝试使用Dugan的复制Excel工作表的答案从一个工作簿到另一个与Powershell,但它导致了一个文件的一部分数据分布在两张表。

这是代码:

$file1 = 'C:\Users\Matthew.Andress\Documents\Excel Test\Book1.xlsx' # source's fullpath $file2 = 'C:\Users\Matthew.Andress\Documents\Excel Test\Book2.xlsx' # destination's fullpath $xl = new-object -c excel.application $xl.displayAlerts = $false # don't prompt the user $wb2 = $xl.workbooks.open($file1, $null, $true) # open source, readonly $wb1 = $xl.workbooks.open($file2) # open target $sh1_wb1 = $wb1.sheets.item(2) # second sheet in destination workbook $sheetToCopy = $wb2.sheets.item('Sheet1') # source sheet to copy $sheetToCopy.copy($sh1_wb1) # copy source sheet to destination workbook $wb2.close($false) # close source workbook w/o saving $wb1.close($true) # close and save destination workbook $xl.quit() spps -n excel 

有什么build议么? 谢谢。

好的,几天后,但是你可以感谢那个周末。 看看这个,看看你喜欢它。

 #Get a list of files to copy from $Files = GCI 'C:\Users\Matt\Documents\Excel Test\' | ?{$_.Extension -Match "xlsx?"} | select -ExpandProperty FullName #Launch Excel, and make it do as its told (supress confirmations) $Excel = New-Object -ComObject Excel.Application $Excel.Visible = $True $Excel.DisplayAlerts = $False #Open up a new workbook $Dest = $Excel.Workbooks.Add() #Loop through files, opening each, selecting the Used range, and only grabbing the first 6 columns of it. Then find next available row on the destination worksheet and paste the data ForEach($File in $Files[0..4]){ $Source = $Excel.Workbooks.Open($File,$true,$true) If(($Dest.ActiveSheet.UsedRange.Count -eq 1) -and ([String]::IsNullOrEmpty($Dest.ActiveSheet.Range("A1").Value2))){ #If there is only 1 used cell and it is blank select A1 [void]$source.ActiveSheet.Range("A1","F$(($Source.ActiveSheet.UsedRange.Rows|Select -Last 1).Row)").Copy() [void]$Dest.Activate() [void]$Dest.ActiveSheet.Range("A1").Select() }Else{ #If there is data go to the next empty row and select Column A [void]$source.ActiveSheet.Range("A2","F$(($Source.ActiveSheet.UsedRange.Rows|Select -Last 1).Row)").Copy() [void]$Dest.Activate() [void]$Dest.ActiveSheet.Range("A$(($Dest.ActiveSheet.UsedRange.Rows|Select -last 1).row+1)").Select() } [void]$Dest.ActiveSheet.Paste() $Source.Close() } $Dest.SaveAs("C:\Users\Matt\Documents\Excel Test\Book1.xlsx",51) $Dest.close() $Excel.Quit() 

这将得到一个Excel文件列表,打开Excel和创build一个新的文档,然后遍历文件列表,打开它们,select列AF,复制这些列,返回到新的工作簿,并select下一个可用的行,并粘贴来自其他工作簿的数据。 然后closures该文件并转到下一个文件。 最后,它将所有数据保存在工作簿中,并closuresexcel。