简体   繁体   中英

How to Combine Excel Workbooks into One Workbook and Name the Worksheets

I am trying to combine several Excel workbooks into a single workbook while naming the worksheets the file name of the copied workbook.

I've tried moving $Worksheet.Name within the for loop and outside. It still only gives a name to the empty worksheet in the new workbook - naming it the last file copied.

$ExcelObject=New-Object -ComObject excel.application
$ExcelObject.visible=$true
$ExcelFiles=Get-ChildItem -Path C:\Users\u1\Documents\Testing

$Workbook=$ExcelObject.Workbooks.add()
$Worksheet=$Workbook.Sheets.Item("Sheet1")

foreach($ExcelFile in $ExcelFiles){

$Everyexcel=$ExcelObject.Workbooks.Open($ExcelFile.FullName)
$Everysheet=$Everyexcel.sheets.item(1)
$Everysheet.Copy($Worksheet)
$Worksheet.Name = [io.path]::GetFileNameWithoutExtension($ExcelFile) 
$Everyexcel.Close()
}

$Workbook.SaveAs("C:\Users\u1\Documents\Testing\New\merged.xlsx")
$ExcelObject.Quit()

The new workbook is created (merged.xlsx) but the worksheets are all named Sheet1(...) except for one empty worksheet that is named the last file in the directory. I also get the following errors. Excel cannot access 'New'. The document may be read-only or encrypted. You cannot call a method on a null-valued expression.

The problem you're facing is that the $Everysheet.Copy($Worksheet) call is copying both the values and the sheet names from $Everysheet and placing it before $Worksheet . You can see the documentation of the Copy method here .

I'm unsure of how you'd track the sheet names to the individual workbooks in order to rename them, however I highly recommend using the ImportExcel module for any Excel-related files. It makes them much easier to work with and only takes a couple seconds to get it working. Moreover it has the benefit of using reading and editing Excel files without needing Microsoft Excel to be installed.

You can accomplish what you're looking to do in a few lines:

$exportExcelPath = "C:\Users\u1\Documents\Testing\New\merged.xlsx"

$excelFiles = Get-ChildItem -Path 'C:\Users\u1\Documents\Testing' -Filter "*.xlsx"
foreach ($excelFile in $excelFiles)
{
    Import-Excel -Path $excelFile.FullName | Export-Excel -Path $exportExcelPath -WorkSheetname ([io.path]::GetFileNameWithoutExtension($excelFile))
}

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