我试图从 GridView
导出到excel。
以下是我的代码:
public override void ExecuteResult(ControllerContext context)
{
HttpContext curContext = HttpContext.Current;
curContext.Response.Clear();
curContext.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
curContext.Response.Charset = "";
curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
curContext.Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
htw.WriteLine("<font size=6>COMPANY<font>");
htw.WriteLine("</br>");
ExcelGridView.HeaderStyle.BackColor = Color.Orange;
ExcelGridView.RenderControl(htw);
ExcelGridView.Rows[2].
htw.WriteLine("<table border=1 bgcolor=#DBA901>");
htw.WriteLine("<tr >");
htw.WriteLine("<td>");
htw.WriteLine("Total");
htw.WriteLine("</td>");
htw.WriteLine("<td colspan=1>");
htw.WriteLine(totalQ);
htw.WriteLine("</td>");
htw.WriteLine("<td>");
htw.WriteLine("</td>");
htw.WriteLine("<td style=mso-number-format:.00>");
htw.WriteLine(totalP);
htw.WriteLine("</td>");
htw.WriteLine("</tr>");
htw.WriteLine("<table>");
byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
MemoryStream s = new MemoryStream(byteArray);
StreamReader sr = new StreamReader(s, Encoding.ASCII);
curContext.Response.Write(sr.ReadToEnd());
curContext.Response.End();
}
我的问题是,在Excel中生成的表中,数字未以十进制格式显示。
例如,123.45将按原样显示,但是123.00将显示为123。我想在这些值中执行.00。我也只想仅在第三和第四列中执行它。
GridView中的值是我想要的,但是在导出到Excel时,仅发生上述问题。
有人可以建议我一个可能的解决方案吗?谢谢。
注意:在上面的代码 excelgridview.rendercontrol(htw); 是GridView和 ExcelGridView 的代码。
尝试epplus库以创建c#的excel:
http://epplus.codeplex.com/
使用此库,您可以使用十进制ANS分隔符将单元格格式设置为数字。
尝试使用StringBuilder(自定义格式工作):
public override void ExecuteResult(ControllerContext context)
{
HttpContext curContext = HttpContext.Current;
curContext.Response.Clear();
curContext.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
curContext.Response.Charset = "";
curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
curContext.Response.ContentType = "application/vnd.ms-excel";
StringBuilder sb = new StringBuilder();
sb.Append("<font size=6>COMPANY<font>");
sb.Append("</br>");
ExcelGridView.HeaderStyle.BackColor = Color.Orange;
ExcelGridView.RenderControl(htw);
ExcelGridView.Rows[2].
sb.Append("<table border=1 bgcolor=#DBA901>");
sb.Append("<tr >");
sb.Append("<td>");
sb.Append("Total");
sb.Append("</td>");
sb.Append("<td colspan=1>");
sb.Append(totalQ);
sb.Append("</td>");
sb.Append("<td>");
sb.Append("</td>");
sb.Append("<td style=mso-number-format:.00>");
sb.Append(totalP);
sb.Append("</td>");
sb.Append("</tr>");
sb.Append("<table>");
byte[] byteArray = Encoding.ASCII.GetBytes(sb.ToString());
MemoryStream s = new MemoryStream(byteArray);
StreamReader sr = new StreamReader(s, Encoding.ASCII);
curContext.Response.Write(sr.ReadToEnd());
curContext.Response.End();
}