Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can PowerShell generate a plain Excel file with multiple sheets?

The Export-Csv cmdlet can export data as a CSV file, which can then be imported in Excel. However, what I'd like to do is to merge different CSV files (with different column definition) into one Excel file having multiple sheets (where each sheet is different).

Can PowerShell call the Excel DLL directly and construct sheets from CSV files?

like image 705
vik santata Avatar asked Dec 05 '22 21:12

vik santata


1 Answers

You can use Excel.ComObject:

## Excel must be installed for this function to work...

Function Merge-CSVFiles
{
Param(
$CSVPath = "C:\CSV", ## Soruce CSV Folder
$XLOutput="c:\temp.xlsx" ## Output file name
)

$csvFiles = Get-ChildItem ("$CSVPath\*") -Include *.csv
$Excel = New-Object -ComObject Excel.Application 
$Excel.visible = $false
$Excel.sheetsInNewWorkbook = $csvFiles.Count
$workbooks = $excel.Workbooks.Add()
$CSVSheet = 1

Foreach ($CSV in $Csvfiles)

{
$worksheets = $workbooks.worksheets
$CSVFullPath = $CSV.FullName
$SheetName = ($CSV.name -split "\.")[0]
$worksheet = $worksheets.Item($CSVSheet)
$worksheet.Name = $SheetName
$TxtConnector = ("TEXT;" + $CSVFullPath)
$CellRef = $worksheet.Range("A1")
$Connector = $worksheet.QueryTables.add($TxtConnector,$CellRef)
$worksheet.QueryTables.item($Connector.name).TextFileCommaDelimiter = $True
$worksheet.QueryTables.item($Connector.name).TextFileParseType  = 1
$worksheet.QueryTables.item($Connector.name).Refresh()
$worksheet.QueryTables.item($Connector.name).delete()
$worksheet.UsedRange.EntireColumn.AutoFit()
$CSVSheet++

}

$workbooks.SaveAs($XLOutput,51)
$workbooks.Saved = $true
$workbooks.Close()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbooks) | Out-Null
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

}

Update the Path for the CSV files, it will create a sheet for each CSV in the folder,

Run it like this:

Merge-CSVFiles -CSVPath C:\CsvFolder -XLOutput C:\ExcelFile.xlsx
like image 166
Avshalom Avatar answered May 12 '23 15:05

Avshalom