Export data to Excel using C#

Posted on 43 930 views 7 comments

In this article I will show you how to export data from generic collection to Excel file.

Assume you are working with list of Car entities. Car has some properties like name, color, and maximum speed. In this case, your entity would look like this:

        public class Car
{
    public string Name { get; set; }
    public string Color { get; set; }
    public int MaximumSpeed { get; set; }
}
    


Let's create some example data for working with:

        List<Car> cars = new List<Car>()
{
    new Car {Name = "Toyota", Color = "Red", MaximumSpeed = 195},
    new Car {Name = "Honda", Color = "Blue", MaximumSpeed = 224},
    new Car {Name = "Mazda", Color = "Green", MaximumSpeed = 205}
};
    


Now, here is the main code for exporting data.

First, you must add reference to your project for using Microsoft.Office.Interop.Excel.dll. This DLL is part of Microsoft Office Primary Interop Assemblies (PIA) Redistibutables.

"A primary interop assembly is a unique, vendor-supplied assembly that contains type definitions (as metadata) of types implemented with COM. There can be only one primary interop assembly, which must be signed with a strong name by the publisher of the COM type library. A single primary interop assembly can wrap more than one version of the same type library."
(For more information please visit: http://msdn.microsoft.com/en-us/library/aax7sdch(v=vs.100).aspx and http://www.microsoft.com/en-us/download/details.aspx?id=3508)

After referencing this DLL you can start using Excel application!
NOTE: pay attention on comments that explains all the code!

        public void ExportToExcel(List<Car> cars)
{
    // Load Excel application
    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

    // Create empty workbook
    excel.Workbooks.Add();

    // Create Worksheet from active sheet
    Microsoft.Office.Interop.Excel._Worksheet workSheet = excel.ActiveSheet;

    // I created Application and Worksheet objects before try/catch,
    // so that i can close them in finnaly block.
    // It's IMPORTANT to release these COM objects!!
    try
    {
        // ------------------------------------------------
        // Creation of header cells
        // ------------------------------------------------
        workSheet.Cells[1, "A"] = "Name";
        workSheet.Cells[1, "B"] = "Color";
        workSheet.Cells[1, "C"] = "Maximum speed";

        // ------------------------------------------------
        // Populate sheet with some real data from "cars" list
        // ------------------------------------------------
        int row = 2; // start row (in row 1 are header cells)
        foreach (Car car in cars)
        {
            workSheet.Cells[row, "A"] = car.Name;
            workSheet.Cells[row, "B"] = car.Color;
            workSheet.Cells[row, "C"] = string.Format("{0} km/h", car.MaximumSpeed);

            row++;
        }

        // Apply some predefined styles for data to look nicely :)
        workSheet.Range["A1"].AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1);

        // Define filename
        string fileName = string.Format(@"{0}\ExcelData.xlsx", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));

        // Save this data as a file
        workSheet.SaveAs(fileName);

        // Display SUCCESS message
        MessageBox.Show(string.Format("The file '{0}' is saved successfully!", fileName));
    }
    catch (Exception exception)
    {
        MessageBox.Show("Exception",
            "There was a PROBLEM saving Excel file!\n" + exception.Message,
            MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
        // Quit Excel application
        excel.Quit();

        // Release COM objects (very important!)
        if (excel != null)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
                
        if (workSheet != null)
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
                
        // Empty variables
        excel = null;
        workSheet = null;

        // Force garbage collector cleaning
        GC.Collect();
    }
}
    

And that's it!
IMPORTANT: be sure to delete all variables and COM objects after quiting Excel application, so that it doesn't hangs in memory.