Click here to Skip to main content
15,845,785 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
hi can anyone help me in exporting a datagridview to an excel. I want to display in excel in specific format, like each row in datagridview should be displayed as columns in excel. File name should not be defined in the code behind. The user should be able to dynamically defined in the save file dialog box. Can anyone help me in code snippet which is quite simple. I used Microsoft.Office.Interop.Excel as reference
Thanks in advance
Suresh Suthar 26-Aug-11 2:30am    
You want the whole code from us? Why would we do this?
If you got stuck somewhere than please post your code, we will surly help you.
maya-123 26-Aug-11 2:41am    

This approach is wrong in principle. Don't export any controls to any documents; export data.

You should have a distinct data layer. Data layer can be bound to UI. If you don't use formal binding, the idea is the same, only implemented "manually": you populate data to you data grid, use events in your data grid to invalidate/update the data layer. In this way, you support synchronization between UI controls and data.

If this is done this way, you always use data persistence, data export/import, reporting, printing and similar functionality on data layer and never on UI controls.

I suggest you learn and analyze applicability of the following architectural patterns ([^]):

MVVM — Model View View Model,[^],

MVC — Model-View-Controller,[^]),

MVA — Model-View-Adapter,–view–adapter[^],

MVP — Model-View-Presenter,[^].
Pay attention for the motivation of those architectures. If you understand it, you would be able to create better design ideas.

Share this answer
Please use the following code lines to export to Excel,

string attachment = "attachment; filename=Test.xls";


Response.AddHeader("content-disposition", attachment);

Response.ContentType = "application/ms-excel";

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);



Share this answer
CyborgForever 26-Aug-11 2:34am    
I just asked for datagridview in windwos
Suresh Suthar 26-Aug-11 2:56am    
You should add/update tag WinForms.

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

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900