GridView導出Excel實現(xiàn)原理與代碼
更新時間:2013年01月10日 16:21:58 作者:
使用GridView來展示數據庫表,幾乎沒對GridView的格式做什么設定,從配置文件中加載SQL,跑出數據就直接綁定到GridView,接下來介紹導出Excel的功能感興趣的朋友可以參考下
為了完成領導交代的任務,這幾天都在做數據展現(xiàn),因為時間比較緊,所以也沒做太復雜,使用GridView來展示數據庫表。幾乎沒對GridView的格式做什么設定,從配置文件中加載SQL,跑出數據就直接綁定到GridView。發(fā)現(xiàn)了一些問題,比如GridView的自動綁定列的寬度是沒法設定的,而此時GridView的表格輸出是不帶寬度信息的,所以導致表格列比較多的時候顯示起來會擠到頁面里面很難看,由于表的列數并不是固定的,所以也沒法很簡單的用模版列的方式做,最后只好直接將表格寬度設置成一個很大的數了事。
此外做了個導出Excel的功能,主要代碼如下:
private void DumpExcel(GridView gv, string FileName)
{//帶格式導出
string style = @"<style> .text { mso-number-format:\@; } </style>";
Response.ClearContent();
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
// Style is added dynamically
Response.Write(style);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
上面的行17的重載函數是必須的,否則會報“GridView要在有run=server的From體內”的錯。
此外,變量style的作用是控制GridView列的樣式,避免發(fā)生excel表中字符前導0被當成數字給截掉這樣的問題, 通過Response.Write方法將其添加到輸出流中。最后把樣式添加到ID列。這一步需要在RowDataBound事件中完成:
1protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("class", "text");
}
}
此外做了個導出Excel的功能,主要代碼如下:
復制代碼 代碼如下:
private void DumpExcel(GridView gv, string FileName)
{//帶格式導出
string style = @"<style> .text { mso-number-format:\@; } </style>";
Response.ClearContent();
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
// Style is added dynamically
Response.Write(style);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
上面的行17的重載函數是必須的,否則會報“GridView要在有run=server的From體內”的錯。
此外,變量style的作用是控制GridView列的樣式,避免發(fā)生excel表中字符前導0被當成數字給截掉這樣的問題, 通過Response.Write方法將其添加到輸出流中。最后把樣式添加到ID列。這一步需要在RowDataBound事件中完成:
復制代碼 代碼如下:
1protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("class", "text");
}
}
相關文章
如何在ASP.NET Core中使用HttpClientFactory
這篇文章主要介紹了如何在ASP.NET Core中使用HttpClientFactory,幫助大家更好的理解和學習使用.net技術,感興趣的朋友可以了解下2021-04-04
MVC4 基礎 枚舉生成 DropDownList 實用技巧
本篇文章小編為大家介紹,MVC4 基礎 枚舉生成 DropDownList 實用技巧。需要的朋友參考下2013-04-04
.NET6?ConfigurationManager的實現(xiàn)及使用方式
這篇文章主要介紹了.NET6?ConfigurationManager的實現(xiàn),我們上面展示的這一部分的ConfigurationManager代碼,其實就是替代了原來的ConfigurationBuilder類的功能,需要的朋友可以參考下2021-12-12

