為了完成領(lǐng)導(dǎo)交代的任務(wù),這幾天都在做數(shù)據(jù)展現(xiàn),因為時間比較緊,所以也沒做太復(fù)雜,使用GridView來展示數(shù)據(jù)庫表。幾乎沒對GridView的格式做什么設(shè)定,從配置文件中加載SQL,跑出數(shù)據(jù)就直接綁定到GridView。發(fā)現(xiàn)了一些問題,比如GridView的自動綁定列的寬度是沒法設(shè)定的,而此時GridView的表格輸出是不帶寬度信息的,所以導(dǎo)致表格列比較多的時候顯示起來會擠到頁面里面很難看,由于表的列數(shù)并不是固定的,所以也沒法很簡單的用模版列的方式做,最后只好直接將表格寬度設(shè)置成一個很大的數(shù)了事。
此外做了個導(dǎo)出Excel的功能,主要代碼如下:
復(fù)制代碼代碼如下:
private void DumpExcel(GridView gv, string FileName)
{//帶格式導(dǎo)出
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的重載函數(shù)是必須的,否則會報“GridView要在有run=server的From體內(nèi)”的錯。
此外,變量style的作用是控制GridView列的樣式,避免發(fā)生excel表中字符前導(dǎo)0被當(dāng)成數(shù)字給截掉這樣的問題, 通過Response.Write方法將其添加到輸出流中。最后把樣式添加到ID列。這一步需要在RowDataBound事件中完成:
復(fù)制代碼代碼如下:
1protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("class", "text");
}
}