Click here to Skip to main content
15,891,567 members
Articles / Programming Languages / C#
Article

Export DataGrid to Excel

Rate me:
Please Sign up or sign in to vote.
3.08/5 (40 votes)
2 Mar 2005CPOL 261.5K   53   53
Easily export DataGrid data to Excel.

Export to Excel (Windows forms only)

This is basically the easiest way to export data from a DataGrid or DataSet to Excel.

I looked all over the Internet and could not find anything useful, only ASP.NET ways of exporting. You just need to add to Excel DLL your references. I have looked over the Internet for the easiest way of doing it and at the end ended up doing this. Just put the code where ever you want to call the event that export the Dataset or DataGrid to Excel.

C#
Excel.ApplicationClass excel = new ApplicationClass();

excel.Application.Workbooks.Add(true); 
DataTable table = DATASETNAME.Tables[0];
int ColumnIndex=0; 
foreach(Datacolumn col in table.Columns)
{   
   ColumnIndex++;
   excel.Cells[1,ColumnIndex]=col.ColumnName;
} 
int rowIndex=0; 
foreach(DataRow row in table.Row) 
{         
    rowIndex++;       
    ColumnIndex=0;         
    foreach(DataColumn col in table.Columns)         
    {  
        ColumnIndex++;                
        excel.Cells[rowIndex+1,ColumnIndex]=row.Cells[col.ColumnName].Text;         
    }
} 
excel.Visible = true; 
Worksheet worksheet = (Worksheet)excel.ActiveSheet; 
worksheet.Activate();
)

I know its not the most difficult thing on the planet to make, but it can be useful to beginners.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionpublic void ExportToExcel(DataGridView gridviewID, string excelFilename) Pin
Member 1363805925-Jan-18 0:44
Member 1363805925-Jan-18 0:44 
Hello

I want to export the data from ACCDB file to Excel and below is my code , i am able to download excel file but its empty pls help me.


string ConnString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Data\Test.accdb";
                DataTable Data = new DataTable();
                using (OleDbConnection conn = new OleDbConnection(ConnString))
                {
                    conn.Open();//break

                    OleDbCommand cmd = new OleDbCommand("select tb3.SeqNo as 'Session Sequence Number',tb3.SessionDate as 'Session Date',tb3.CustomerName as 'Customer Name',tb3.RepID as 'Rep ID',tb3.RepName as 'Rep Name',CaseRef as 'Ticket No',PracticeName as 'Practice Name',PostCode as 'Post Code',PhoneManner as 'Phone Manner',Satisfaction,iif (Satisfaction='EXCELLENT',5, iif (Satisfaction='VERY GOOD' ,4, iif (Satisfaction='GOOD' ,3, iif (Satisfaction='NEUTRAL' ,2, iif (Satisfaction='POOR' ,1))))) as Ratings,Ratings/5*100 as 'Percentage' , Consultant,CustomerComments as 'Customer Comments',Recommendation from tb1,tb3 where tb3.SeqNo=tb1.SeqNo and tb3.SessionDate between #" + fromdate + "# and #" + todate + "#", conn);
                    OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
                    adapter.Fill(Data);
                    conn.Close();
                    dataGridView1.DataSource = Data;

                    Microsoft.Office.Interop.Excel.Application objexcelapp = new Microsoft.Office.Interop.Excel.Application();
                    objexcelapp.Application.Workbooks.Add(Type.Missing);
                    objexcelapp.Columns.ColumnWidth = 25;
                    for (int i = 1; i < gridviewID.Columns.Count + 1; i++)
                    {
                        objexcelapp.Cells[1, i] = gridviewID.Columns[i - 1].HeaderText;
                    }
                    /*For storing Each row and column value to excel sheet*/
                    for (int i = 0; i < gridviewID.Rows.Count; i++)
                    {
                        for (int j = 0; j < gridviewID.Columns.Count; j++)
                        {
                            if (gridviewID.Rows[i].Cells[j].Value != null)
                            {
                                objexcelapp.Cells[i + 2, j + 1] = gridviewID.Rows[i].Cells[j].Value.ToString();
                            }
                        }
                    }
                    MessageBox.Show("Your excel file exported successfully at d:\\" + excelFilename + ".xlsx");
                    objexcelapp.ActiveWorkbook.SaveCopyAs("d:\\" + excelFilename + ".xlsx");
                    objexcelapp.ActiveWorkbook.Saved = true;
                }
            }

GeneralMy vote of 5 Pin
LodJordan30-Sep-11 2:05
LodJordan30-Sep-11 2:05 
GeneralMy vote of 5 Pin
darshan yadav8-Mar-11 0:33
darshan yadav8-Mar-11 0:33 
GeneralMy vote of 2 Pin
dcustode28-Jul-10 21:35
dcustode28-Jul-10 21:35 
GeneralBetter use a non-COM solution Pin
pfgrid18-Jul-10 8:52
pfgrid18-Jul-10 8:52 
GeneralVB.net Solution Pin
THROWBACK459-Jun-10 4:03
THROWBACK459-Jun-10 4:03 
Questionif my datagrid is from xml? Pin
gs_virdi24-May-10 23:21
gs_virdi24-May-10 23:21 
Generalexport to excel Pin
sdeepa1-Dec-08 23:34
sdeepa1-Dec-08 23:34 
QuestionMake column fonts BOLD and format text ?? Pin
Gurdeep Singh Toor21-Apr-08 9:38
Gurdeep Singh Toor21-Apr-08 9:38 
GeneralDatagrid Pin
dddaaannn25-Mar-08 8:40
dddaaannn25-Mar-08 8:40 
AnswerRe: Datagrid Pin
shamahamid9-Jul-08 7:26
shamahamid9-Jul-08 7:26 
GeneralRe: Datagrid Pin
Wamuti3-Sep-09 22:44
Wamuti3-Sep-09 22:44 
GeneralRe: Datagrid Pin
darshan yadav8-Mar-11 1:59
darshan yadav8-Mar-11 1:59 
Generaldatagrid data to excel Pin
Jose Lora9-Jan-08 11:39
Jose Lora9-Jan-08 11:39 
Questionsame code used with datagrid? Pin
spidermike9-Jan-08 8:30
spidermike9-Jan-08 8:30 
GeneralSolution International users Pin
xor.be14-Nov-07 2:16
xor.be14-Nov-07 2:16 
GeneralRe: Solution International users Pin
Walaza16-Mar-08 21:34
Walaza16-Mar-08 21:34 
Questionconvert xml data to excel format Pin
shajoh11-Apr-07 23:51
shajoh11-Apr-07 23:51 
QuestionWhat if I use an ArrayList as the DataSource? Pin
SerDai11-Apr-07 3:51
SerDai11-Apr-07 3:51 
QuestionDataGrid to excel in c#.net Pin
ashwinishilpa9-Oct-06 0:15
ashwinishilpa9-Oct-06 0:15 
QuestionHow To Customize Cells Styles Pin
GianniCic31-Aug-06 21:51
GianniCic31-Aug-06 21:51 
GeneralIf we want to create two worksheet Pin
serkanuz14-Aug-06 5:45
serkanuz14-Aug-06 5:45 
GeneralRe: If we want to create two worksheet Pin
FilipKrnjic9-Jul-09 4:46
FilipKrnjic9-Jul-09 4:46 
GeneralException and warning Pin
Asbj0rn20-Jul-06 7:39
Asbj0rn20-Jul-06 7:39 
GeneralRe: Exception and warning Pin
Asbj0rn20-Jul-06 9:10
Asbj0rn20-Jul-06 9:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.