This sample query data from database and bind it to datagrid.
Datagrid will be exported to excel file in HTML steaming
Code in aspx.cs
protected void btnSubmit_Click(object sender, ImageClickEventArgs e)
{
DataGrid myDataGrid = new DataGrid();
System.Data.SqlClient.SqlConnection mysqlConnection;
System.Data.SqlClient.SqlCommand mysqlCommand;
System.Data.SqlClient.SqlDataReader dReader;
String queryString = @" TYPE IN YOUR SQL HERE ";
mysqlConnection = new SqlConnection(MyConstant.connectionString);
mysqlCommand = new System.Data.SqlClient.SqlCommand(queryString, mysqlConnection);
mysqlConnection.Open();
SqlDataAdapter da = new SqlDataAdapter(mysqlCommand);
DataSet ds = new DataSet();
da.Fill(ds);
myDataGrid.DataSource = ds.Tables[0];
myDataGrid.DataBind();
// convert the output fields to string format
String strStyle = "";
for (int intTemp = 0; intTemp < ds.Tables[0].Rows.Count; intTemp++)
{
for (int j = 0; j < myDataGrid.Items[intTemp].Cells.Count; j++) { myDataGrid.Items[intTemp].Cells[j].Attributes.Add("class", "text"); }
}
mysqlConnection.Close();
//export to excel
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel"; Response.Charset = ""; Response.AddHeader("content-disposition", "attachment;filename=ExportExcel.xls"); Response.ContentEncoding = Encoding.Unicode;
Response.BinaryWrite(Encoding.Unicode.GetPreamble());
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
myDataGrid.RenderControl(oHtmlTextWriter);
Response.Write(strStyle);
Response.Write(oStringWriter.ToString());
Response.End();
}
Subscribe to:
Post Comments (Atom)
2 comments:
你show 出離d code 好差,唔該收埋佢. 唔好教壞人啦
Hi, guantanamera121212
Post a Comment