在项目中我们经常会遇到要求将一些数据导出成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="婚否">
<%# boolean.parse(eval_r("married").tostring())==true?"是":"否" %>
</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();
response.contenttype = "application/ms-word";
response.addheader("content-disposition", "attachment;filename=data.doc");
参考博客1:http://blog.csdn.net/zhoufoxcn/archive/2008/05/16/2450642.aspx
参考博客2:http://blog.csdn.net/rickyll/archive/2009/10/22/4714517.aspx