Search code examples
excelpowershellcsvexport-to-csvexcel.application

Merge multiple CSV into one without using Excel.Application


I created a PowerShell script that allows me to merge multiple .CSV into one .XLSX file.

It works well on my computer:

$path = "C:\Users\Francesco\Desktop\CSV\Results\*"
$csvs = Get-ChildItem $path -Include *.csv
$y = $csvs.Count
Write-Host "Detected the following CSV files: ($y)"
Write-Host " "$csvs.Name"`n"
$outputfilename = "Final Registry Results"
Write-Host Creating: $outputfilename
$excelapp = New-Object -ComObject Excel.Application
$excelapp.SheetsInNewWorkbook = $csvs.Count
$xlsx = $excelapp.Workbooks.Add()
for ($i=1;$i -le $y;$i++) {
    $worksheet = $xlsx.Worksheets.Item($i)
    $worksheet.Name = $csvs[$i-1].Name
    $file = (Import-Csv $csvs[$i-1].FullName)
    $file | ConvertTo-Csv -Delimiter "`t" -NoTypeInformation | clip
    $worksheet.Cells.Item(1).PasteSpecial() | Out-Null
}

$output = "C:\Users\Francesco\Desktop\CSV\Results\Results.xlsx"
$xlsx.SaveAs($output)
$excelapp.Quit()

The problem is that I need to run this on several servers and servers are well known for not having Office installed so I cannot use Excel.Application.

Is there a way to merge multiple CSV into one CSV or XLSX without using Excel.Application and saving each CSV into a different sheet?


Solution

  • Time has passed and I have found a new solution: Install-Module -Name ImportExcel

    This way the module takes care of the job like in this script.