Wednesday, January 15, 2014

ExcelHelper C# Class

ExcelHelper C# Class

This class has a single static method called ConvertExcelToCsv, which takes an Excel file and creates a CSV file. One thing to note is that it does NOT delete the original Excel file, that is up to you if you want to do that.
Since Excel files can have multiple sheets, there is the optional parameter of specifying what sheet to write as the CSV file. If you leave it blank it will default to the first one in the workbook.

using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
namespace jarloo
{
    public static class ExcelHelper
    {
        public static void ConvertExcelToCsv(string source, string destination, int sheetNumber=1)
        {
            if (File.Exists(destination)) File.Delete(destination);
            Application xl = new Application();
            try
            {
                Workbook workbook = xl.Workbooks.Open(source);
                Worksheet ws = (Worksheet) workbook.Sheets[sheetNumber];
                ws.SaveAs(destination, XlFileFormat.xlCSV);
                Marshal.ReleaseComObject(ws);
            }
            finally
            {
                xl.DisplayAlerts = false;
                xl.Quit();
                Marshal.ReleaseComObject(xl);
            }
        }
    }
}


Example Converting Excel to CSV in C#

All you need to do to convert the file after you’ve added the ExcelHelper class is execute the method like so:











namespace Jarloo
{
    class Program
    {
        static void Main(string[] args)
        {
            ExcelHelper.ConvertExcelToCsv(@"c:tempsample.xlsx",@"c:tempsample.csv");
        }
    }

No comments:

Post a Comment