Friday, September 11, 2015

How to convert CSV to EXCEL using C#

It is possible using the EPPLUS .net library. It is free and available in epplus.codeplex.com. You have to pass both CSV and the EXCEL file path where it should be saved. The ExcelTextFormat class has more conditions, based on that it reads the CSV file. Check the below console application sample code that accomplish that task.
static void Main(string[] args)
{
 string csvFilePath = @"D:\sample.csv";
 string excelFilePath = @"D:\sample.xls";

 string worksheetsName = "TEST";
 bool firstRowIsHeader = false;

 var excelTextFormat = new ExcelTextFormat();
 excelTextFormat.Delimiter = ',';
 excelTextFormat.EOL = "\r";

 var excelFileInfo = new FileInfo(excelFilePath);
 var csvFileInfo = new FileInfo(csvFilePath);

 using (ExcelPackage package = new ExcelPackage(excelFileInfo))
 {
  ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);
  worksheet.Cells["A1"].LoadFromText(csvFileInfo, excelTextFormat, OfficeOpenXml.Table.TableStyles.Medium25, firstRowIsHeader);
  package.Save();
 }

 Console.WriteLine("Converted!");
 Console.ReadLine();
}
EPPLUS Setup

The EPPLUS can be installed through Visual Studio Nuget package also. Follow the below steps to install it.

  • Right click the Visual Studio solution and select "Manage NuGet Packages for Solution".
  • And in the window search for EPPlus. 
  • From the searched list select EPPlus and click install.

No comments:

Post a Comment