Created
November 25, 2025 08:28
-
-
Save hugotai101/0d7d8fad56446aed505f295018666723 to your computer and use it in GitHub Desktop.
Combine multiple csv file to Excel file with ClosedXml, using csv filename as excel sheet name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Globalization; | |
| using System.IO; | |
| using ClosedXML.Excel; | |
| using CsvHelper; | |
| namespace ConsoleApp1 | |
| { | |
| class Program | |
| { | |
| static void Main() | |
| { | |
| string csvFolder = @"C:\hugotemp"; | |
| string excelPath = @"C:\hugotemp\big6" + ".xlsx"; | |
| using (var workbook = new XLWorkbook()) | |
| { | |
| foreach (var csvFile in Directory.GetFiles(csvFolder, "*.csv")) | |
| { | |
| string csvFileName = Path.GetFileNameWithoutExtension(csvFile); | |
| string csvPath = csvFile; | |
| // Step 1: Read CSV with CsvHelper | |
| using (var reader = new StreamReader(csvPath)) | |
| using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) | |
| { | |
| var records = csv.GetRecords<dynamic>(); | |
| // Step 2: Create Excel workbook with ClosedXML | |
| { | |
| var worksheet = workbook.Worksheets.Add(csvFileName); | |
| int row = 1; | |
| bool headerWritten = false; | |
| foreach (var record in records) | |
| { | |
| var dict = (IDictionary<string, object>)record; | |
| // Write header row once | |
| if (!headerWritten) | |
| { | |
| int col = 1; | |
| foreach (var key in dict.Keys) | |
| { | |
| worksheet.Cell(row, col).Value = key; | |
| col++; | |
| } | |
| headerWritten = true; | |
| row++; | |
| } | |
| // Write data row | |
| int dataCol = 1; | |
| foreach (var value in dict.Values) | |
| { | |
| worksheet.Cell(row, dataCol).Value = value.ToString(); | |
| dataCol++; | |
| } | |
| row++; | |
| } | |
| worksheet.Columns().AdjustToContents(); | |
| } | |
| } | |
| Console.WriteLine($"CSV converted to Excel: {excelPath}"); | |
| } | |
| // Step 3: Save Excel file | |
| workbook.SaveAs(excelPath); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment