如何使用PowerShell来select和复制新工作簿中的数据所在的列和行。

我想要select并复制新工作簿中存在数据的列和行。

我发现这个链接,帮助我做到了上述。 如何使用PowerShell来复制几个Excel工作表,并创build一个新的?

但我想要的唯一变化是,在下面给出的计划中,他们获取前6列,而我想检查有数据的列,并拿起它们。 任何人都可以帮助我。

#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() 

在此先感谢萌

使用$rowMax = ($sheet.UsedRange.Rows).count来检查具有值的行数。 循环遍历$ rowMax并将值存储在一个variables中。

检查我的post获取Excel值