protected void ToExcel(GridView gv,string name) {
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
// 如果設定為 GetEncoding("GB2312");匯出的檔案將會出現亂碼!!!
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/ms-excel";//設定輸出檔案型別為excel檔案。
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
gv.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@;");
}
}
protected void btnToExcel_Click(object sender, EventArgs e)
{
if (gvStat.Rows.Count > 0 && gvStat.Visible == true) {
ToExcel(gvStat, "from " + ViewState["StartDate"].ToString() + " to " + ViewState["EndDate"].ToString());
}
else if (gvUser.Rows.Count > 0 && gvUser.Visible == true) {
ToExcel(gvUser, "from " + ViewState["StartDate"].ToString() + " to " + ViewState["EndDate"].ToString());
}
}