Tengo varios archivos de Excel que tienen el mismo número de hojas con los mismos nombres de hoja. Las mismas hojas en todos los archivos de Excel que tienen los mismos encabezados. Así que quiero una idea de cómo fusionar todas las hojas coincidentes en varios archivos de Excel y crear un nuevo archivo de Excel mediante secuencias de comandos con Powershell.
Cualquier sugerencia ayuda.
Gracias.
Si el número de columnas es el mismo en las diferentes hojas de cálculo de Excel, entonces debería poder usar el siguiente código para fusionar los archivos.
El código usa métodos de la interfaz NamedRange de la API de Excel.
Código de ejemplo: (solo recuerde cambiar las rutas y los nombres de archivo a su entorno)
# Create an instance of Excel $Excel = New-Object -ComObject Excel.Application # Find the files you want to process $Files = Get-ChildItem -Path C:\Temp -Filter *.xlsx # Create a target workbook and worksheet called 'Sheet1' $TargetWorkbook = $Excel.Workbooks.add() $TargetWorksheet = $TargetWorkbook.Sheets.Item("Sheet1") # Loop through our Excel files foreach($File in $Files) { # Open the workbook and get the first sheet $SourceWorkbook=$Excel.Workbooks.Open($File.FullName) $SourceWorksheet=$SourceWorkbook.Sheets.Item(1) # Calculate the end column letter $EndColumn = [char]([int][char]'A' + $SourceWorksheet.UsedRange.Columns.Count - 1) # Activate the source worksheet $SourceWorksheet.activate() # Get the total number of rows in the sheet $SourceLastRow = $SourceWorksheet.UsedRange.Rows.Count + 1 # Calculate what our start row should be # A1 for the first worksheet only to include the headers $StartRow = (& { If ($TargetWorkSheet.UsedRange.rows.count -eq 1) { "A1" } Else { "A2" } } ) # Get the range of data and copy it to the clipboard $SourceRange = $SourceWorksheet.Range("$($StartRow):$EndColumn$SourceLastRow") $SourceRange.copy() # Activate the target worksheet $TargetWorksheet.activate() # Get the total number of rows in the sheet $TargetLastRow = $TargetWorkSheet.UsedRange.Rows.Count if ($TargetWorkSheet.UsedRange.Rows.Count -ne 1) { # If this isn't the first sheet we've processed, add one additional row $TargetLastRow++ } # Get the target range and paste the data $TargetRange = $TargetWorksheet.Range("A$($TargetLastRow):$EndColumn$($SourceRange.Rows.Count)") $TargetWorksheet.Paste($TargetRange) # Disable showing alerts, otherwise a notification about # large amounts of data on the clipboard will be shown $Excel.DisplayAlerts = $false # Close the source workbook $SourceWorkbook.Close() } # Re-enable showing alerts $Excel.DisplayAlerts = $true # Save the workbook to the desired path $TargetWorkbook.SaveAs("C:\Temp\Merged.xlsx") # Quit Excel $Excel.Quit() Si sus hojas tienen diferentes números de columnas, aún podría usar el código anterior, sin embargo, deberá realizar algunos cambios en las $SourceRange , $TargetRange y $EndColumn para tener esto en cuenta.