Response.Buffer = true;
Response.ClearContent();
////指定http名称和值
Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode("StudentScores", System.Text.Encoding.UTF8) + ".xls");
//指定文件类型
Response.ContentType = "application/excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
StringWriter sw = new StringWriter();
ExcelGridView.AllowPaging = false;
this.ExcelGridView.DataSource = dtStudentScore;
ExcelGridView.DataBind();
//HtmlTextWriter 输出流
HtmlTextWriter htw = new HtmlTextWriter(sw);
ExcelGridView.RenderControl(htw);
string style = @"<style> .text { mso-number-format:\@; } </style> "; //单元格式为文本格式
//sw写入到http输出流
Response.Output.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
ExcelGridView.Visible = false;
加上<style> .text { mso-number-format:\@; } </style>这段CSS应该就可以正常显示
也可以通过RowDataBound来将指定的单元格设置成文本格式
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e),增加导出Excel功能
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("class", "text"); //设置第列为文本格式
e.Row.Cells[2].Attributes.Add("class", "text"); //设置第列为文本格式
e.Row.Cells[6].Attributes.Add("class", "text"); //设置第列为文本格式
e.Row.Cells[7].Attributes.Add("class", "text"); //设置第列为文本格式
}
}
2008/7/14 17:23:40
回答者:
吴畏
提问者对于答案的评价:我试过gridview的格式用gv_RowDataBound方法可以,不过用了style我这边还是不能正常显示;由于我这边使用的是ultrawebgrid,研究了下,不过还是不知道在什么事件里增加e.Row.Cells[1].Attributes.Add("class", "text"),纯粹没事研究下,所以算了,不过还是谢谢你们的回答。