码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET输出EXCEL表格的几种方法(总结修改)

时间:2014-06-12 15:02:36      阅读:384      评论:0      收藏:0      [点我收藏+]

标签:style   code   http   tar   ext   color   

这几天要从数据库导出EXCEL表格,就找了N钟方法,经测试,下面的方法比较的好用一点。都是经过输入DataTable而导出的。不过导出的EXCEL都不是正规的EXCEL格式,只能说是HTML格式的,导出的再导入进数据库就会出现问题了。想导入的话用EXCEL打开另存为EXCEL格式就好了

1.利用DataRow直接输出,经测试,没有乱码。
        public bool LendOutExcel(string strFileName, DataTable DT)
        {
            try
            {
                //清除Response缓存内容
                HttpContext.Current.Response.Clear();
                //缓存输出,并在完成整个响应之后将其发送
                HttpContext.Current.Response.Buffer = true;
                //strFileName指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt .htm
                strFileName = strFileName + ".xls";
                //设置输出流的HTPP字符集,确定字符的编码格式
                //HttpContext.Current.Response.Charset = "UTF-8";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                //下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName));
                //Response.ContentType指定文件类型.可以为application/ms-excel,application/ms-word,application/ms-txt,application/ms-html或其他浏览器可直接支持文档
                HttpContext.Current.Response.ContentType = "application/ms-excel";

                string colHeaders = "", ls_item = "";
                int i = 0;
                //定义表对象与行对像,同时用DataSet对其值进行初始化
                DataRow[] myRow = DT.Select("");
                //取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
                for (i = 0; i < DT.Columns.Count - 1; i++)
                {
                    colHeaders += DT.Columns[i].Caption.ToString() + "\t";
                }
                colHeaders += DT.Columns[i].Caption.ToString() + "\n";
                //向HTTP输出流中写入取得的数据信息
                HttpContext.Current.Response.Write(colHeaders);
                //逐行处理数据
                foreach (DataRow row in myRow)
                {
                    //在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n
                    for (i = 0; i < DT.Columns.Count - 1; i++)
                        ls_item += row[i].ToString() + "\t";
                    ls_item += row[i].ToString() + "\n";
                    //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据   
                    HttpContext.Current.Response.Write(ls_item);
                    ls_item = "";
                }
                //写缓冲区中的数据到HTTP头文件中
                HttpContext.Current.Response.End();

                return true;
            }
            catch
            {
                return false;
            }
        }

输出为:学院活动表.xls

活动名称 活动时间 活动地点 发起人 承担人 批准人 活动概况 参与人 备注
第5次9                                              2008-7-27 0:00:00 HBU_ 1 shenxian_ 1   jiaoren there where is a will,there is a way ren ren ren ren people haha,hehe,xixi
第5次8                                              2008-7-27 0:00:00 HBU_ 2 shenxian_ 2 xianren jiaoren there where is a will,there is a way ren ren ren ren people haha,hehe,xixi
第5次7                                              2008-7-27 0:00:00 HBU_ 3 shenxian_ 3 xianren jiaoren there where is a will,there is a way ren ren ren ren people haha,hehe,xixi
第5次6                                              2008-7-27 0:00:00 HBU_ 4 shenxian_ 4 xianren jiaoren there where is a will,there is a way ren ren ren ren people haha,hehe,xixi
第5次5                                              2008-7-27 0:00:00 HBU_ 5 shenxian_ 5 xianren jiaoren there where is a will,there is a way ren ren ren ren people haha,hehe,xixi
第5次9                                              2008-7-27 0:00:00 HBU_ 1 shenxian_ 1   jiaoren there where is a will,there is a way ren ren ren ren people haha,hehe,xixi
第5次8                                              2008-7-27 0:00:00 HBU_ 2 shenxian_ 2 xianren jiaoren there where is a will,there is a way ren ren ren ren people haha,hehe,xixi
第5次7                                              2008-7-27 0:00:00 HBU_ 3 shenxian_ 3 xianren jiaoren there where is a will,there is a way ren ren ren ren people haha,hehe,xixi
第5次6                                              2008-7-27 0:00:00 HBU_ 4 shenxian_ 4 xianren jiaoren there where is a will,there is a way ren ren ren ren people haha,hehe,xixi
第5次5                                              2008-7-27 0:00:00 HBU_ 5 shenxian_ 5 xianren jiaoren there where is a will,there is a way ren ren ren ren people haha,hehe,xixi

 

2.利用GridView输出,经测试,有的输出有乱码
        public bool LendOutExcel(string strFileName, DataTable DT)
        {
            try
            {
                //清除Response缓存内容
                HttpContext.Current.Response.Clear();
                //缓存输出,并在完成整个响应之后将其发送
                HttpContext.Current.Response.Buffer = true;
                //strFileName指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt .htm
                strFileName = strFileName + ".xls";
                //设置输出流的HTPP字符集,确定字符的编码格式
                //HttpContext.Current.Response.Charset = "UTF-8";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                //下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName));
                //Response.ContentType指定文件类型.可以为application/ms-excel,application/ms-word,application/ms-txt,application/ms-html或其他浏览器可直接支持文档 
                HttpContext.Current.Response.ContentType = "application/ms-excel";

                //用GridView输出
                GridView dv = new GridView();
                dv.DataSource = DT;
                dv.DataBind();
                try
                {
                    dv.Page.EnableViewState = false;
                }
                catch
                { }
                System.IO.StringWriter swBody = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter hwBody = new System.Web.UI.HtmlTextWriter(swBody);
                //dv表示输出GridView,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件
                dv.RenderControl(hwBody);
                //消除乱码特别设定,非常规方法
                string strExcel = "";
                strExcel = "";
                strExcel += hwBody.InnerWriter.ToString();
                HttpContext.Current.Response.Write(strExcel);
                HttpContext.Current.Response.End();

                return true;
            }
            catch
            {
                return false;
            }
        }

输出为:工作表.xls
<div>
<table cellspacing="0" rules="all" border="1" style="border-collapse:collapse;">
   <tr>
    <th scope="col">课程编号</th><th scope="col">课程名称</th><th scope="col">课序号</th><th scope="col">任课教师</th>
   </tr><tr>
    <td>ASP.NET-0</td><td>ASP.NET</td><td>0</td><td>shenxian</td>
   </tr><tr>
    <td>VB-0</td><td>VB</td><td>0</td><td>任志波</td>
   </tr><tr>
    <td>操作系统-0</td><td>操作系统</td><td>0</td><td>郝杰</td>
   </tr><tr>
    <td>计算机网络-0</td><td>计算机网络</td><td>0</td><td>杨秀丹</td>
   </tr><tr>
    <td>数据库-0</td><td>数据库</td><td>0</td><td>郝杰</td>
   </tr><tr>
    <td>数据库应用技术-0</td><td>数据库应用技术</td><td>0</td><td>wjy</td>
   </tr><tr>
    <td>数据库应用技术-1</td><td>数据库应用技术</td><td>1</td><td>wjy</td>
   </tr>
</table>
</div>

 

3.利用DataGrid输出,导出没问题,有没有乱码的问题没注意

protected void btnLendIn_Click(object sender, EventArgs e)
    {
    DataTable dt = LIE.LendInDT();
    StringWriter stringWriter = new StringWriter();
    HtmlTextWriter htmlWriter = new HtmlTextWriter( stringWriter );
    DataGrid excel = new DataGrid();
    System.Web.UI.WebControls.TableItemStyle AlternatingStyle = new TableItemStyle();
    System.Web.UI.WebControls.TableItemStyle headerStyle = new TableItemStyle();
    System.Web.UI.WebControls.TableItemStyle itemStyle = new TableItemStyle();
    AlternatingStyle.BackColor = System.Drawing.Color.LightGray;
    headerStyle.BackColor =System.Drawing.Color.LightGray;
    headerStyle.Font.Bold = true;
    headerStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
    itemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;;

    excel.AlternatingItemStyle.MergeWith(AlternatingStyle);
    excel.HeaderStyle.MergeWith(headerStyle);
    excel.ItemStyle.MergeWith(itemStyle);
    excel.GridLines = GridLines.Both;
    excel.HeaderStyle.Font.Bold = true;
    excel.DataSource = dt.DefaultView;    //输出DataTable的内容
    excel.DataBind();
    excel.RenderControl(htmlWriter);

    string filestr ="d:\\1.xls";   //filePath是文件的路径
    int pos = filestr.LastIndexOf("\\");
    string file = filestr.Substring(0,pos);
    if( !Directory.Exists( file ) )
    {
     Directory.CreateDirectory(file);
    }
    System.IO.StreamWriter sw = new StreamWriter(filestr);
    sw.Write(stringWriter.ToString());
    sw.Close();
}


输出的内容为:1.xls
<table cellspacing="0" rules="all" border="1" style="border-collapse:collapse;">
<tr align="center" style="background-color:LightGrey;font-weight:bold;">
   <td>课程编号</td><td>课程名称</td><td>课序号</td><td>任课教师</td>
</tr><tr align="center">
   <td>ASP.NET-0</td><td>ASP.NET</td><td>0</td><td>shenxian</td>
</tr><tr align="center" style="background-color:LightGrey;">
   <td>VB-0</td><td>VB</td><td>0</td><td>任老师</td>
</tr><tr align="center">
   <td>操作系统-0</td><td>操作系统</td><td>0</td><td>郝老师</td>
</tr><tr align="center" style="background-color:LightGrey;">
   <td>计算机网络-0</td><td>计算机网络</td><td>0</td><td>杨老师</td>
</tr><tr align="center">
   <td>数据库-0</td><td>数据库</td><td>0</td><td>郝老师</td>
</tr><tr align="center" style="background-color:LightGrey;">
   <td>数据库应用技术-0</td><td>数据库应用技术</td><td>0</td><td>wjy</td>
</tr><tr align="center">
   <td>数据库应用技术-1</td><td>数据库应用技术</td><td>1</td><td>wjy</td>
</tr>
</table>

 

本文转自http://hi.baidu.com/zagelover/item/f143b9118342bbe99913d675

经测试 第一种方法可行 其余方法暂时还没用到

导出excel时 如果是页面[ajax页面]中含有<asp:UpdatePanel  和<asp:ScriptManager控件时  如果你的事件按钮在UpdatePanel 范围内会报错

解决办法就是把时间按钮放到UpdatePanel 范围之外

ASP.NET输出EXCEL表格的几种方法(总结修改),布布扣,bubuko.com

ASP.NET输出EXCEL表格的几种方法(总结修改)

标签:style   code   http   tar   ext   color   

原文地址:http://www.cnblogs.com/lczblog/p/3782006.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!