Click here to Skip to main content
Click here to Skip to main content

Export DataGrid to Excel

By , 2 Mar 2005
 

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.

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)

About the Author

JJ G
Web Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberLodJordan30 Sep '11 - 2:05 
Very good. solved my problems.
GeneralMy vote of 5memberdarshan yadav8 Mar '11 - 0:33 
Help me a lot but i have reference problm.i cant find Excel.ApplicationClass reference.
modified on Tuesday, March 8, 2011 7:53 AM

GeneralMy vote of 2memberdcustode28 Jul '10 - 21:35 
Code doesn't work.
GeneralBetter use a non-COM solutionmemberpfgrid18 Jul '10 - 8:52 
The the PFGrid.NET has this feature included without using a COM-libary. Excel must not be installed on your computer to use the feature:
 
PFGrid.NET
GeneralVB.net SolutionmemberTHROWBACK459 Jun '10 - 4:03 
Imports System.Windows.Forms
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel
 
Private Sub btnExportToExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExportToExcel.Click
Dim excel As Excel.ApplicationClass = New ApplicationClass()
 
excel.Application.Workbooks.Add(True)
 
Dim dtDataTable As System.Data.DataTable = dsHoldTheData.Tables(0)
 
Dim ColumnIndex As Integer = 0
 
For Each col As DataColumn In dtDataTable.Columns
ColumnIndex += 1
excel.Cells(1, ColumnIndex) = col.ColumnName
Next
 
Dim rowIndex As Integer = 0
 
For Each row As DataRow In dtDataTable.Rows
rowIndex += 1
ColumnIndex = 0
For Each col As DataColumn In dtDataTable.Columns
ColumnIndex += 1
excel.Cells(rowIndex + 1, ColumnIndex) = row.Item(col.ColumnName).ToString
Next
Next
 
excel.Visible = True
Dim worksheet As Worksheet = DirectCast(excel.ActiveSheet, Worksheet)
worksheet.Activate()
 
End Sub
Questionif my datagrid is from xml?membervirdigs24 May '10 - 23:21 
Thx for sharing the code, but kindly do help this newbie by telling that what if my dataGridview is populated using ReadXml() in my formload event?
 
What shall I do in this Export_ButtonClick function? Using the below code:
Excel.ApplicationClass excelSheet = new Excel.ApplicationClass();
            excelSheet.Application.Workbooks.Add(true);
            DataSet ds = new DataSet();
            DataTable dt = ds.Tables[cdtext];
            int columnIndex = 0;
            foreach (DataGridViewColumn column in dt.Columns)
            {
                columnIndex++;
                excelSheet.Cells[1, columnIndex] = column.HeaderText;
            }
            int rowIndex = 0;
            foreach (DataGridViewRow row in dt.Rows)
            {
                rowIndex++;
                columnIndex = 0;
                foreach (DataGridViewColumn column in dt.Columns)
                {
                    columnIndex++;
                    excelSheet.Cells[rowIndex + 1, columnIndex] = row.Cells[column.Name].FormattedValue;
                }
            }
            excelSheet.Visible = true;
            Excel.Worksheet workSheet = (Excel.Worksheet)excelSheet.ActiveSheet;
            ((Excel._Worksheet)workSheet).Activate();
 
NullReferenceException is handled both in dt.Columns & dt.Rows. What should I do now?
Generalexport to excelmembersdeepa1 Dec '08 - 23:34 
Is the code you provided is for c#.net window application? can you please give more details for it.Like adding reference which excel should be selected.look forward for more.
QuestionMake column fonts BOLD and format text ??membergurdeeptoor21 Apr '08 - 9:38 
Hi the article is great and working perfect.. !
 
Just a little thing I need is How to make the Column hearders bold and May be need them to make visualize by having different color.
 
Any Idea ??
 
Regards
GeneralDatagridmemberdddaaannn25 Mar '08 - 8:40 
How can I export from a DataGridView instead of a Dataset ?
 
Thanks.
AnswerRe: Datagridmembershamahamid9 Jul '08 - 7:26 
This the modified code to use a datagridview instead of a dataset
 
using Excel = Microsoft.Office.Interop.Excel;
....
 
Excel.ApplicationClass excelSheet = new Excel.ApplicationClass();
excelSheet.Application.Workbooks.Add(true);
int columnIndex = 0;
foreach (DataGridViewColumn column in dgResults.Columns)
{
columnIndex++;
excelSheet.Cells[1, columnIndex] = column.HeaderText;
}
int rowIndex = 0;
foreach (DataGridViewRow row in dgResults.Rows)
{
rowIndex++;
columnIndex = 0;
foreach (DataGridViewColumn column in dgResults.Columns)
{
columnIndex++;
excelSheet.Cells[rowIndex + 1, columnIndex] = row.Cells[column.Name].FormattedValue;
}
}
excelSheet.Visible = true;
Excel.Worksheet workSheet = (Excel.Worksheet)excelSheet.ActiveSheet;
workSheet.Activate();
GeneralRe: DatagridmemberWamuti3 Sep '09 - 22:44 
Hi. Nice addition to the article. Just what i needed. But what is dlResults? If it is a variable from DataGrid, it contains no reference to dgResults.Columns.
 
shamahamid wrote:
foreach (DataGridViewColumn column in dgResults.Columns)
{
columnIndex++;
excelSheet.Cells[1, columnIndex] = column.HeaderText;
}

 
Please assist.
 
Wamuti: Any man can be an island, but islands to need water around them!
Edmund Burke: No one could make a greater mistake than he who did nothing because he could do only a little.

GeneralRe: Datagridmemberdarshan yadav8 Mar '11 - 1:59 
thanks
GeneralRe: Datagridmembergg423723 Oct '09 - 2:19 
You could do that with GemBox.Spreadsheet .NET component for manipulating Excel files.
 
Here is an example how to Import or Export DataGrid to Excel using GemBox.Spreadsheet.
Generaldatagrid data to excelmemberJose Lora9 Jan '08 - 11:39 
Hello, I'm a very beginner C# programmer. I don't know how to add Excel dll to references. Can somebody help me with this, please?. Also, I'm trying, after I click a button, to export the data in a datagrid, not a dataset, displayed on a window forms app an excel sheet.
 
Thank
Questionsame code used with datagrid?memberspidermike9 Jan '08 - 8:30 
hi
 
i have a datagrid/datagridview with some data in a form. how can I export this to excel with the code sample?
really need help,
 
thnx!
Mike
GeneralSolution International usersmemberxor.be14 Nov '07 - 2:16 
First of all, thx for this code.
It really came in handy.
 
I ran into a problem with incompatible values.
This happens when the language of excel is different the the windows environment settings.
 
you have to manually set the culture to the same one as excell
 
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
 
So my full code is = ( don't mind the timers .. it takes a while with 5000+ rows. So i added a progressbar since people will be doing this over vpn too)
 
private void export_To_XLS()
{
timer1.Start();
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
 
Excel.ApplicationClass excel = new Excel.ApplicationClass();
excel.Application.Workbooks.Add(true);
System.Data.DataTable table = ds.Tables[0];
int ColumnIndex=0;
foreach(DataColumn col in table.Columns)
{
ColumnIndex++;
excel.Cells[1,ColumnIndex]=col.ColumnName;
}
int rowIndex=0;
foreach(System.Data.DataRow row in table.Rows)
{
rowIndex++;
ColumnIndex=0;
foreach(DataColumn col in table.Columns)
{
ColumnIndex++;
excel.Cells[rowIndex+1,ColumnIndex]=row[col.ColumnName].ToString();
}
}
excel.Visible = true;
Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet;
worksheet.Activate();

 
timer1.Stop();
}

 

Hope it helps Smile | :)
xor
GeneralRe: Solution International usersmemberWalaza16 Mar '08 - 21:34 
Hi,
My spreadsheet only shows the headings. It does not show the rest of the data. I wrote the code exactly as yours. Please help!
 
Mvelo Walaza
Developer
Telkom SA

Questionconvert xml data to excel formatmembershajoh11 Apr '07 - 23:51 
i am unable to convert my xml data in to excel format and save it in workbook
 
shashank
QuestionWhat if I use an ArrayList as the DataSource?memberSeFe11 Apr '07 - 3:51 
I use an ArrayList item as the DataGrid's DataSource.
How do I export it in this case?
 
I'd also like to keep the formatting I defined with DataGridTableStyle.
 
Thanks!
QuestionDataGrid to excel in c#.netmemberashwinishilpa9 Oct '06 - 0:15 
I have datagrid with images in the header and checkbox as item template in the first column.
 
I need to export this datagrid in to excel.
 
For that first I need to replace these image buttons with literal text.
 
Can anyone help with this???
 
Thanks in Advance
 
Ashwini
QuestionHow To Customize Cells StylesmemberGianniCic31 Aug '06 - 21:51 
Hi,
 
the source code is perfect! Thanks
 
Now i need to edit the cells styles : for example the background color,make text bold and so on...
 
How i can do that?
 
Thanks
GeneralIf we want to create two worksheetmemberserkanuz14 Aug '06 - 5:45 
Hi,
 
Your code is very usefull. But I have a problem.
 
I'm customizing dataset object and converting to excel but. I would like to export modified and not modified datasets as seperate worksheets.
 
How can I do it?
 
Thank you.
 

 
Serkan UZ
GeneralRe: If we want to create two worksheetmemberFilipKrnjic9 Jul '09 - 4:46 
Hi serkanuz,
 
Easiest and fastest way to deal with Excel files in C# is with some 3rd party component like GemBox .NET Excel component. It is free for commercial use if you need less then 150 rows.
 
For more information how to use GemBox Spreadsheet check out a list of articles about component.
 
Filip
GeneralException and warningmemberAsbj0rn20 Jul '06 - 7:39 
Hi.
I'm using Visual C# 2005 Express, and I've got Excel 2003.
 
I get an exception on this line:
excel.Application.Workbooks.Add(true);
COMException was unhandled.
Gammelt format eller ugyldig typebibliotek. -> something like...Old format or invalid type library.
Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))
 
I also get a warning on this line.
worksheet.Activate();
Warning     1     Ambiguity between method 'Microsoft.Office.Interop.Excel._Worksheet.Activate()' and non-method 'Microsoft.Office.Interop.Excel.DocEvents_Event.Activate'. Using method group.     C:\Stairway2.0\Stairway program\Stairway2.0\Stairway2.0\Table.cs     91     23     Stairway2.0

GeneralRe: Exception and warningmemberAsbj0rn20 Jul '06 - 9:10 
I found the solution for the exception.
All info is here: http://support.microsoft.com/kb/320369
 
But I still got the warning though.

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 3 Mar 2005
Article Copyright 2005 by JJ G
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid