Aspnet导出System.Web.UI.Control到Word或Excel
作者:陆金龙
发表时间:2014-12-11 23:50
1. 导出Excel或Word 功能代码
////// 将Web控件导出 /// ///控件实例 ///类型:Excel或Word public void ExpertControl(System.Web.UI.Control source, DocumentType type) { //设置Http的头信息,编码格式 if (type == DocumentType.Excel) { //Excel Response.AppendHeader("Content-Disposition","attachment;filename=r.xls"); Response.ContentType = "application/ms-excel"; } else if (type == DocumentType.Word) { //Word Response.AppendHeader("Content-Disposition","attachment;filename=r.doc"); Response.ContentType = "application/ms-word"; } Response.Charset = "UTF-8"; Response.ContentEncoding = System.Text.Encoding.UTF8; //关闭控件的视图状态 source.Page.EnableViewState =false; //初始化HtmlWriter StringWriter writer = new StringWriter() ; HtmlTextWriter htmlWriter = new HtmlTextWriter(writer); source.RenderControl(htmlWriter); //输出 Response.Write(writer.ToString()); Response.End(); }
2.文档类型定义
public enum DocumentType
{
Word,
Excel
}
3.调用方法示例及说明
ExpertControl(this, DocumentType.Word); //这是将整个页面导出为Word
//this可以为具体的控件如datagrid/dataList或page表示当前页,DocumentType为导出的文件格式(Excel/word)
注意:当为datagrid或dataList控件时,在导出Excel/word文件时,将出现"类型“DataGridLinkButton”的控件“DataGrid1__ctl14__ctl1
”必须放在具有 runat=server 的窗体标记内。"错误!
解决:在页面中重写Page基类的VerifyRenderingInServerForm方法
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}