0

I have multiple Excel files with different names in path.

e.g. C:\Users\XXXX\Downloads\report

Each file has a fixed number of columns.

e.g. Date | Downtime | Response

I want to create a new Excel file with merge of all Excel data. New column should be added with client name in which i want to enter file name. Then each Excel file data append below one by one.

e.g. Client name | Date | Downtime | Response

Below code can able to append all excel data but now need to add Client name column.

$path = "C:\Users\XXXX\Downloads\report"

#Launch Excel, and make it do as its told (supress confirmations)
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $True
$Excel.DisplayAlerts = $False
$Files = Get-ChildItem -Path $path

#Open up a new workbook
$Dest = $Excel.Workbooks.Add()

#Loop through files, opening each, selecting the Used range, and only grabbing the first 5 columns of it. Then find next available row on the destination worksheet and paste the data
ForEach($File in $Files)
{
    $Source = $Excel.Workbooks.Open($File.FullName,$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","E$(($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","E$(($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("$path\Merge.xls")
$Dest.close()
$Excel.Quit()

Suggest any effective way to do this. Please provide links if available.

Convert XLS to XLSX :

$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault
$excel = New-Object -ComObject excel.application
$excel.visible = $true
$folderpath = "C:\Users\xxxx\Downloads\report\*"
$filetype ="*xls"
Get-ChildItem -Path $folderpath -Include $filetype | 
ForEach-Object `
{
    $path = ($_.fullname).substring(0,($_.FullName).lastindexOf("."))
    "Converting $path to $filetype..."
    $workbook = $excel.workbooks.open($_.fullname)

    $workbook.saveas($path, $xlFixedFormat)
    $workbook.close()
}
$excel.Quit()
$excel = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()
2
  • 2
    SO is not a place where other people rewrite code you found somewhere on the web to your requirements. Being a member for almost 8 years you should know that by now. Apr 10, 2019 at 9:17
  • Yes, thats why i write to suggest a way. Don't want anyone to rewrite it. Anyway i am looking into it. Will update if able to figure out.
    – rAJ
    Apr 10, 2019 at 9:23

2 Answers 2

1

If you are willing to use the external module Import-Excel, you could simply loop through the files like so:

$report_directory = ".\reports"

$merged_reports = @()

# Loop through each XLSX-file in $report_directory
foreach ($report in (Get-ChildItem "$report_directory\*.xlsx")) {

    # Loop through each row of the "current" XLSX-file
    $report_content = foreach ($row in Import-Excel $report) {
        # Create "custom" row
        [PSCustomObject]@{
            "Client name" = $report.Name
            "Date"        = $row."Date"
            "Downtime"    = $row."Downtime"
            "Response"    = $row."Response"
        }
    }

    # Add the "custom" data to the results-array
    $merged_reports += @($report_content)
}

# Create final report
$merged_reports | Export-Excel ".\merged_report.xlsx"

Please note that this code is not optimized in terms of performance but it should allow you to get started

3
  • Failed to read C:\Users\XXXX\Downloads\report\aucondeco0100-mla-uat.xls At C:\Program Files\WindowsPowerShell\Modules\ImportExcel\5.4.5\ImportExcel.psm1:356 char:20
    – rAJ
    Apr 11, 2019 at 6:20
  • Well ... since I don't know how the files look like, I can't say what's the problem. Maybe it's because XLS is an archaic format. You could use something like ConvertTo-ExcelXlsx $report -Force to reformat the XLS into XLSX so you may be able to use that XLSX-File in the Import-Excel-loop
    – Razorfen
    Apr 11, 2019 at 7:14
  • 1
    ok cool. it just need to convert xls to xlsx file first and then to use your code. I am updating the conversion code in the question. Thanks for the help.
    – rAJ
    Apr 11, 2019 at 7:51
0
Get-ChildItem *.xlsx | ForEach-Object {
$XLSX = Import-XML -Path $_.FullName -Delimiter ","
$FileName = $_.Name

$XLSX | Select-Object *,@{N='Filename';E={$FileName}} | Export-XML $_.FullName -NTI 

}

1
  • 1
    Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community? Jun 27 at 0:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.