I have two Gridview in my Web application.I need ,while clicking the (ExcelExpot) button the values to be Export in Excel Accordingly Sheet1 and Sheet2.
protected void ExportToExcel()
{
this.GridView1.EditIndex = -1;
Response.Clear();
Response.Buffer = true;
string connectionString = (string)ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection sqlconnection = new SqlConnection(connectionString);
String sqlSelect = "select * from login";
sqlconnection.Open();
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(sqlSelect, connectionString);
//DataTable dt1
DataTable dt1 =new DataTable();
mySqlDataAdapter.Fill(dt1);
//LinQ Query for dt2
var query = (from c in dt.AsEnumerable()
select new {id= c.Field<string>("id"),name=c.Field<string>("name"),city=c.Field<string>("city")}) ;
DataTable dt2 = new DataTable();
d2=query.CopyToDatatable();
DataSet ds=new DataSet();
ds.Tabls.Add(dt1);
ds.Tabls.Add(dt2);
Excel.Application excelHandle1 = PrepareForExport(ds);
excelHandle1.Visible = true;
}
// code for PrepareForExport(ds);
PrepareForExport(ds)
{
two tables in two worksheets of Excel...
}
See Question&Answers more detail:os