在项目中我们经常会遇到要求将一些数据导出成Excel或者Word表格的情况
前台代码:
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvPersonList" runat="server" >
<Columns>
<asp:BoundField DataField="Id" HeaderText="编号" />
<asp:BoundField DataField="Name" HeaderText="姓名" />
<asp:TemplateField HeaderText="性别">
<ItemTemplate>
<%# eval_r("Sex").ToString()=="true"?"男":"女" %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Age" HeaderText="年龄" />
<asp:TemplateField HeaderText="婚否">
<ItemTemplate>
<%# Boolean.Parse(eval_r("Married").ToString())==true?"是":"否" %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnToExcel" runat="server" OnClick="btnToExcel_Click" Text="导出Excel" />
<asp:Button ID="btnToWord" runat="server" OnClick="btnToWord_Click" Text="导出Word" />
</div>
</form>
后台代码
protected void btnToExcel_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
Page page = new Page();
HtmlForm form = new HtmlForm();
GridView1.EnableViewState = false;
page.EnableEventValidation = false;
page.DesignerInitialize();
page.Controls.Add(form);
form.Controls.Add(GridView1);
page.RenderControl(htw);
Response.Clear();
Response.Buffer = true;
//设置导出文件的格式
Response.ContentType = "application/vnd.ms-excel";
//假定导出的文件名为data.xls
Response.AddHeader("Content-Disposition", "attachment;filename=data.xls");
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.Default;
Response.Write(sb.ToString());
Response.End();
}
protected void btnToWord_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
Page page = new Page();
HtmlForm form = new HtmlForm();
GridView1.EnableViewState = false;
page.EnableEventValidation = false;
page.DesignerInitialize();
page.Controls.Add(form);
form.Controls.Add(GridView1);
page.RenderControl(htw);
Response.Clear();
Response.Buffer = true;
//设置导出文件的格式
Response.ContentType = "application/ms-word";
//假定导出的文件名为data.xls
Response.AddHeader("Content-Disposition", "attachment;filename=data.doc");
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.Default;
Response.Write(sb.ToString());
Response.End();
}
参考博客1:http://blog.csdn.net/zhoufoxcn/archive/2008/05/16/2450642.aspx
参考博客2:http://blog.csdn.net/rickyll/archive/2009/10/22/4714517.aspx