下面代碼是C# .net輸出word和excel檔案的公告函數,使用方法先建立gridview填充資料,然後用時copy如下函數到cs頁面,調用方法 OutExcel(GridviewName, "File name.xls"); OutWord(GridviewName, "File name.doc");
指定gridview的 名字和檔案名稱即可!
//輸出到excel的函數,可直接copy到 cs頁面
private void OutExcel(GridView dg, string name)
{
dg.Visible = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
name = "attachment;filename=" + name;
Response.AppendHeader("Content-Disposition", name);
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType = "application/ms-excel";
dg.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
dg.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
//輸出到word的函數,可直接copy到 cs頁面
private void OutWord(GridView dg, string name)
{
//string name="lessons.xls";
dg.Visible = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
name = "attachment;filename=" + name;
Response.AppendHeader("Content-Disposition", name);
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType = "application/ms-word";
dg.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
dg.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
//重載VerifyRenderingInServerForm方法,調用頁面必須加入否則會提示錯誤
public override void VerifyRenderingInServerForm(Control control)
{
}
//調用方法 OutWord(Student, "File name.doc");
protected void Button1_Click(object sender, EventArgs e)
{
OutWord(Student, "File name.doc");
}
//調用方法 OutExcel(Student, "File name.xls");
protected void Button2_Click(object sender, EventArgs e)
{
OutExcel(Student, "File name.xls");
}