Link to home
Start Free TrialLog in
Avatar of Philippe Renaud
Philippe RenaudFlag for Canada

asked on

Help exporting DatAGridView to Excel

Hello EE,

I have a DataGridview I would like to export to excel. I know how to do it with for next...
my problem is the column order in the excel needs to be a little bit different.

lets say Columns in the dataGrid are :

TotalCredit      01Credit     02Credit   03Credit    Code      Desc     Total Debit


I would like in excel the order to be:

Code    Desc    TotalCredit   Total Debit    01Credit     02Credit   03Credit



How can I achieve this with code example ?

thanks
ASKER CERTIFIED SOLUTION
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Philippe Renaud

ASKER

So I would do something like :

From state In DataGridview1.Datasource.AsEnumerable _

...

and then select the order I want in linq ?

then after a for next with 'state' to create my excel ?
cast your datasource as dataset or datatable (if it is what they are originally)

state can be replace with whatever you want. in my demo, I used state because I am looping a states table
yea I know for the 'state' I just copied paste your line :)
get the datasource of your gridview, create a new datatable with columns as per your needs.
Fill this new datatable with data from your gridview datasource.

Create a new gridview and assign this new datatable as its datasource.
Then save this gridview to excel, here is a sample code:-
DataTable dtOriginal=gridView1.DataSource;
DataTable dtNew=new DataTable();
//add columns to datatable as required and copy the data

DataGrid rv=new DataGrid();
rv.DataSource=dtNew;

Open in new window

here are few ways to do this:-
http://www.codeproject.com/Articles/164582/8-Solutions-to-Export-Data-to-Excel-for-ASP-NET