首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

在线,导出excel

2013-04-05 
在线求助,导出excel现在有这样的一个多表头,但是表头导出的效果不是我想要的现在我想先在excel中写好表头,

在线求助,导出excel
现在有这样的一个多表头,但是表头导出的效果不是我想要的
现在我想先在excel中写好表头,把datagridview中的数据导进去该怎么做? 导出 excel datagridview
[解决办法]
直接到DataGridView里的数据源DataTable
  

public static void TableToExcel(DataTable dt, string fileName, bool saveFile)
        {
            StringWriter stringWriter = new StringWriter();
            #region 设置数字为文本形式,避免长数字转为科学计数法而丢失0
            string strStyle = "<style>td{mso-number-format:'\\@';}</style>";

            stringWriter.WriteLine(strStyle);
            #endregion
            HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
            DataGrid excel = new DataGrid();

            TableItemStyle AlternatingStyle = new TableItemStyle();
            TableItemStyle headerStyle = new TableItemStyle();
            TableItemStyle itemStyle = new TableItemStyle();
            headerStyle.Font.Bold = true;

            headerStyle.HorizontalAlign = HorizontalAlign.Center;
            itemStyle.HorizontalAlign = 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;
            excel.DataBind();
            excel.RenderControl(htmlWriter);

            int fileN = fileName.LastIndexOf('\\');
            string tmpName = fileName.Substring(fileN + 1);

            // 文件的保存路径
            string DownloadFilePath = fileName;
            
            


            // 如果需要保存文件则保存文件在服务器端
            if (!Directory.Exists(DownloadFilePath) && saveFile)
            {
                StreamWriter sw = new StreamWriter(DownloadFilePath, false, Encoding.GetEncoding("utf-7"));
                sw.Write(stringWriter.ToString());                
                sw.Close();
            }


            // 下载文件到客户端

            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.GetEncoding("GB2312");
            //curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + tmpName);
            curContext.Response.AppendHeader("Content-Disposition", "attachment;   filename=" + System.Web.HttpUtility.UrlEncode(tmpName, System.Text.Encoding.UTF8));
            curContext.Response.Charset = "";

            curContext.Response.Write(stringWriter.ToString());
            curContext.Response.End();    


        }

        

热点排行