Skip to content

Instantly share code, notes, and snippets.

@hugotai101
Created November 25, 2025 08:28
Show Gist options
  • Select an option

  • Save hugotai101/0d7d8fad56446aed505f295018666723 to your computer and use it in GitHub Desktop.

Select an option

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
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