在.net里把数据库的数据用excel导出后怎么让它按我们所想的格式排列好呢?就是导出excel时数据能够排列好,不会显得乱七八糟的。

解决方案 »

  1.   


    /// <summary>
            /// GridView导出到exel
            /// </summary>
            /// <param name="ColNum">隐藏的列号</param>
            /// <param name="GridName">GridView名称</param>
            public static void GridViewToExel(int[] ColNum, GridView GridName, string TitleName)
            {
                try
                {
                    foreach (int i in ColNum)
                    {
                        GridName.Columns[i].Visible = false;
                    }                int ColCount = GridName.Columns.Count - ColNum.Length;
                    System.Web.HttpContext.Current.Response.Clear();
                    System.Web.HttpContext.Current.Response.Buffer = true;
                    System.Web.HttpContext.Current.Response.Charset = "utf-8";
                    System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Files.xls");                GridName.AllowPaging = false;
                    GridName.BorderWidth = Unit.Pixel(1);                System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                    System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。                 System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
                    System.Web.UI.HtmlTextWriter htlwriter = new System.Web.UI.HtmlTextWriter(oStringWriter);                GridName.RenderControl(htlwriter);
                    StringBuilder strTitle = new StringBuilder();
                    strTitle.Append("<table id=Content2 border=\"2\" width=770px;>");//office 2000,office XP 不支持字体大小〈font size=...></font>等 office 2003支持
                    strTitle.Append("<tr><TD align=center colspan=\"" + ColCount + "\"><h3>" + TitleName + "</h3></td></tr>");
                    //strTitle += "<tr><td align=center>" + "" + "</td></tr>";
                    //strTitle += "<tr><td height=30></td></tr><tr><td>";
                    //strTitle += lab_Title.Text.ToString();                strTitle.Append("</td></tr></table> ");
                    System.Web.HttpContext.Current.Response.Write(strTitle);                System.Web.HttpContext.Current.Response.Output.Write(oStringWriter.ToString());
                    System.Web.HttpContext.Current.Response.Flush();
                    System.Web.HttpContext.Current.Response.End();                GridName.AllowPaging = true;
                    GridName.DataBind();
                    GC.Collect();
                }
                catch (Exception ex) 
                {
                    ex.ToString();
                }
            }这个你可以参考一下,