您的位置:首页 > Web前端 > CSS

Response.Write Table 方式导出Excel 添加样式

2015-11-10 15:47 821 查看
在asp.net中导出Excel常用  Response.Write  Table 的方式导出Excel 

但是导出的报表样式可能不符合要求 ,比如说 表格边框 Table的边框宽度最小只能是 1 

而导出的Excel报表的边框还是太粗 想让边框变细些 



我们可以这样做:

先用Response.Write 导出 一个Excel表格,这时用记事本或其他文本编辑器打开 只能看到一些 类似与html的代码 

用office打开导出的Excel表格,编辑表格边框,右击边框 选择设置单元格格式 选择"边框"标签 外边框 然后在右边选择要设置的边框样式,保存



然后以XML格式打开该Excel文件,根据表格中的数据找到刚才设置边框的表格



,查看该单元格的class,根据class名称定位到 样式内容,刚才我设置的是 A0302单元格 ,class是x129



可以看到 单元格的样式的CSS代码

复制border :.5pt solid black; 这条,在输出时加入图中代码

[csharp]view
plaincopyprint?

Response.Clear();  

Response.Buffer = true;  

Response.Charset = "gb2312";  // gb2312、utf-8、ISO8859-1(Latin-1)  

Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(Exceltitle + ".xls", Encoding.UTF8));  

Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");//设置输出流为简体中文  

Response.ContentType = "application/msExcel";//设置输出文件类型为excel文件。   

Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");  

span style="background-color: rgb(255, 255, 153);"> Response.Write("<style>.border  { border:.5pt solid black; }</style>");//添加样式</span>  

this.EnableViewState = true;  

System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);  

System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);  

System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);  

tb.RenderControl(oHtmlTextWriter);//将服务器控件的内容输出  

Response.Write(oStringWriter.ToString());  

Response.End();  

然后在创建单元格时 为单元格设置class属性

[csharp]view
plaincopyprint?

private TableCell CreateCell(string text, int withs)  

        {  

            TableCell tc = new TableCell();  

            tc.BorderColor = System.Drawing.Color.Black;  

            <span style="background-color: rgb(255, 204, 204);">//tc.BorderWidth = 1;</span> //这句一定要注释  

            tc.Font.Size = new FontUnit("9");  

            tc.Text = text;  

            tc.Width = withs;  

            tc.HorizontalAlign = HorizontalAlign.Center;  

            tc.VerticalAlign = VerticalAlign.Middle;  

            <span style="background-color: rgb(255, 255, 153);">tc.Attributes.Add("class", "border");//添加样式</span>  

            return tc;  

        }  

Ok ,再次导出 大功告成!!

当然在

[csharp]view
plaincopyprint?

<span style="background-color: rgb(255, 255, 153);">Response.Write("<style>.border  { border:.5pt solid black; }</style>");//添加样式</span>  

中也可以加入其他样式代码,为了保证Excel对所加样式的支持,最好是先在Excel中设置
然后粘贴过来

来自:http://blog.csdn.net/li_1042237864/article/details/6718212
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: