欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

简单实用的.net DataTable导出Execl

程序员文章站 2023-11-15 17:26:34
datatable导出execl代码太简单,我们直接看代码。 复制代码 代码如下:    protected void btnprint_c...

datatable导出execl
代码太简单,我们直接看代码。

复制代码 代码如下:

    protected void btnprint_click(object sender, eventargs e)
    {
        string strpath = "mfout" + datetime.now.tostring("yyyymmddhhmmssfff") + ".xls";
        datagrid dg = new datagrid();
        dg.datasource = dtmain;
        dg.databind();
        response.clear();
        response.addheader("content-disposition", "attachment;filename=" + strpath + "");
        response.charset = "gb2312";
        response.contentencoding = system.text.encoding.utf8;//不设置会有乱码
        response.contenttype = "application/vnd.xls";
        system.io.stringwriter stringwrite = new system.io.stringwriter();
        system.web.ui.htmltextwriter htmlwrite = new htmltextwriter(stringwrite);
        dg.rendercontrol(htmlwrite);
        response.write(stringwrite.tostring());
        response.end();
    }
    public override void verifyrenderinginserverform(control control)
    {
        //这个方法不能删除掉 导出时要用到,不然会报错:
        //类型“gridview”的控件“ctl00_contentplaceholder1_gridview1”必须放在具有 runat=server 的窗体标记内
    }