65.9K
CodeProject is changing. Read more.
Home

A Simple Way to Export DataGridViews/Lists to Excel

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Oct 5, 2012

CPOL
viewsIcon

21993

This article focuses on a Very simple and Robust way to export Data to EXCEL

Introduction 

This article describes exporting to Excel without using any 3rd party DLLs, Office Interops, or any other tool. This is a simple method to get the exporting done and it's a robust way. This is a suggestive solution for all who are involved in developing similar tools/utilities to do similar stuff.

Background 

This mechanism is inspired by the XML/HTML compatible Excel engine.

Using the Code 

The below method is written for the exporting functionality. You can simply get this copied into your apps. 

private static string ExportDataGridView2EXCEL(DataGridView pDataGridView, string pFilePath)
{
    String file2exp = "<HTML><BR/><TABLE BORDER = 1 " + 
           "><TR><TH style= background-color:#E4E2E2>#</TH>";

    // Headers
    foreach (DataGridViewColumn col in pDataGridView.Columns)
    {
        if (col.Visible)
        {
            file2exp += "<TH style= background-color:#E4E2E2>" + 
                        col.HeaderText + "</TH>";
        }
    }
    file2exp += "</TR>";
    
    int cnt = 1; // row counter

    foreach (DataGridViewRow row in pDataGridView.Rows)
    {
        if (!row.Visible)
            continue;
        file2exp += "<TR><TD>" + cnt++ + "</TD>";
        foreach (DataGridViewCell cell in row.Cells)
        {
            if (!cell.Visible)
                continue;

            file2exp += "<TD>" + 
                 GetFormattedValue(cell) + "</TD>";
        }
        file2exp += "</TR>";
    }

    file2exp += "</TABLE></HTML>";

    File.WriteAllText(pFilePath, file2exp);

    return "Y";
}  

And just call this method wherever you want to export DataGridViews. 

Points of Interest

This is a cool way that is suggested for use for exporting data to Excel. Further this can be enhanced by formatting cell by cell for many purposes. Hope you enjoy this.