ASP.NET 匯出方式
匯出方式
void Export()
{
//匯出 Excel 或 Word
string fileName = "Questionnaire" + DateTime.Now.ToShortDateString() + ".xls"; //excel
//string fileName = _topicid+".doc"; //word
Response.Clear();
//指定下載的檔名
Response.AddHeader("content-disposition",
"attachment;filename=" + fileName);
Response.ContentType = "application/vnd.ms-excel"; //excel
// Response.ContentType = "application/vnd.ms-word"; //word
//加入下面兩行才可正常顯示中文
Response.Write("<head><meta http-equiv=Content-Type content=text/html;" +
"charset=UTF-8></head>");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
GridView3.RenderControl(htw);
//若要只匯出 GridView1, 請將 this 改為 GridView1
Response.Write(sw.ToString());
Response.End();
}
若為Gridview 要添加下一段
public override void VerifyRenderingInServerForm(Control control)
{
// '處理'GridView' 的控制項 'GridView' 必須置於有 runat=server 的表單標記之中
}
Gridview 分頁
private void ExportExcel()
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "BIG5";
string Excel_ShortTime = DateTime.Now.ToShortDateString() + "_" +
DateTime.Now.Hour.ToString() +
DateTime.Now.Minute.ToString() +
DateTime.Now.Second.ToString();
Response.AppendHeader("Content-Disposition", "attachment;filename=TEST_" + Excel_ShortTime + ".xls");
Response.ContentEncoding = Encoding.GetEncoding("BIG5");
Response.ContentType = "application/ms-excel";
GridView1.EnableViewState = false;
GridView1.AllowPaging = false;
GridViewBind(GridView1, LoadData());
StringWriter objStringWriter = new StringWriter();
HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);
GridView1.RenderControl(objHtmlTextWriter);
Response.Write(objStringWriter.ToString());
Response.End();
GridView1.AllowPaging = true;
GridViewBind(GridView1, srcTable);
}_
以上資訊,網路收集....感恩!!
0 留言