一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

c# 导入word或excel文档代码

时间:2010-12-25 编辑:简简单单 来源:一聚教程网

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

<%@ page language="c#" enableeventvalidation="false" autoeventwireup="true" codefile="default.asp教程x.cs" inherits="_default" %> 

    private void dbexport()
    {
        httpcontext.current.response.charset = "gb2312";
        httpcontext.current.response.contentencoding = encoding.utf8;
        //有部分文章里使用的是utf7,是因为在特殊情况下中文会出现乱码;这里建议使用utf8,msdn中提到utf7没有utf8安全性高;
        //下面两行可以保证其正确性,使用方法见代码中
        //response.write("");
        //response.write("");
        //这里对文件名称时行了编码处理,以防止出现中文名称乱码的现象
        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("");
        httpcontext.current.response.write(tw.tostring());
        response.write("");

        response.flush();
        response.close();
    }
    //这个方法需要重写,否则会报错
    public override void verifyrenderinginserverform(control control)
    {

    }

热门栏目