ASP.NET导出Excel或Word文件格式

    //说明下 EnableEventValidation="false"的使用;
    //在页面上添加了输入型服务器控件时(如 TextBox),就需要设置为false了,否则会报错;也就是关闭页面验证,默认是开启的。

 //就是这个样子

<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

private   void  DBExport()
    {
        HttpContext.Current.Response.Charset 
=   " GB2312 " ;
        HttpContext.Current.Response.ContentEncoding 
=  Encoding.UTF8;
        
// 有部分文章里使用的是UTF7,是因为在特殊情况下中文会出现乱码;这里建议使用UTF8,MSDN中提到UTF7没有UTF8安全性高;
        
// 下面两行可以保证其正确性,使用方法见代码中
        
// Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
        
// Response.Write("</body></html>");
        
// 这里对文件名称时行了编码处理,以防止出现中文名称乱码的现象
        HttpContext.Current.Response.AppendHeader( " Content-Disposition " " attachment;filename= "   +  HttpUtility.UrlEncode( " 文件名称.xls " , Encoding.UTF8));
        
// 导出excel格式,因为格式不同,所以文件名称后缀要根据实际情况进行调整(.xls)
        HttpContext.Current.Response.ContentType  =   " vnd.ms-excel " ;
        
// 导出word格式,因为格式不同,所以文件名称后缀要根据实际情况进行调整(.doc)
        
// HttpContext.Current.Response.ContentType = "vnd.ms-word";
        
// 导出html格式,因为格式不同,所以文件名称后缀要根据实际情况进行调整(.html)
        
// HttpContext.Current.Response.ContentType = "text/HTML";

        
// 还有两种写法好像是可以直接输出图像,没来得及加以考证,不过应该不是像上边一样改下格式就可以的,应该是先创建图形对象才可以设置Response.ContentType才能输出
        
// 哪位有简单的方式希望贴出来,学习下,谢谢
        
// HttpContext.Current.Response.ContentType = "image/GIF";
        
// HttpContext.Current.Response.ContentType = "image/JPEG";

        
// 说明下 divid 是什么,这里应该是你要转出的控件,可以是服务器控件也可以的HTML控件(要加上  runat="server"否则这里是找不到控件的)
        
// 我的页面里是一个 div id="divid" runat="server" 里放了一个GridView用于显示数据
        divid.Page.EnableViewState  =   false ;
        System.IO.StringWriter tw 
=   new  System.IO.StringWriter();
        HtmlTextWriter hw 
=   new  HtmlTextWriter(tw);
        divid.RenderControl(hw);
        
// 下边的三行才是数据的输出
        Response.Write( " <html><head><meta http-equiv=Content-Type content=\ " text / html; charset = utf - 8 \ " > " );
        HttpContext.Current.Response.Write(tw.ToString());
        Response.Write(
" </body></html> " );

        Response.Flush();
        Response.Close();
    }
    
// 这个方法需要重写,否则会报错
     public   override   void  VerifyRenderingInServerForm(Control control)
    {

    }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值