I am working on a script where I am trying to merge multiple csv into a single Excel file with csv filename as different sheet.
All the csv files have the same number of columns and name.
I don't have Excel installed on my server, so I've written this code using ImportExcel
:
#Install-Module ImportExcel -scope CurrentUser
$path="C:\Scripts" #target folder
cd $path;
$csvs = Get-ChildItem .\* -Include *.csv
$csvCount = $csvs.Count
Write-Host "Detected the following CSV files: ($csvCount)"
foreach ($csv in $csvs) {
Write-Host " -"$csv.Name
}
$excelFileName = $path + "\" + $(get-date -f yyyyMMdd) + "_combined-data.xlsx"
Write-Host "Creating: $excelFileName"
foreach ($csv in $csvs) {
$csvPath = $path + $csv.Name
$worksheetName = $csv.Name.Replace(".csv","")
Write-Host " - Adding $worksheetName to $excelFileName"
Import-Csv -Path $csvPath | Export-Excel -Path $excelFileName -WorkSheetname $worksheetName
The script is taking time and executing without any issue but the Excel sheet is not being generated.
Please can you help me find and fix the issue in this script?
$csvPath = $path + $csv.Name
is missing the backslash. UseJoin-Path
instead. [2]$worksheetName = $csv.Name.Replace(".csv","")
-->$worksheetName = $csv.BaseName
, but remember that Microsoft Excel does not allow worksheet name longer than 31 characters. [3] Change$csvs = Get-ChildItem .\* -Include *.csv
to$csvs = Get-ChildItem .\* -Filter '*.csv' -File
– Theo