gridView 导出时使用以下方法时:
/// <summary>
/// 导出的方法
/// <param name="ctrl">要导出的控件</param>
/// <param name="FileName">导出的文件名</param>
/// </summary>
public static void GridViewToExcel(Control ctrl, String FileName)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
System.Web.UI.Page page = new System.Web.UI.Page();
HtmlForm form = new HtmlForm();
GridView gv = (GridView)ctrl;
gv.EnableViewState = false;
// grdLoginDetails.
// Deshabilitar la validación de eventos, sólo asp.net 2
page.EnableEventValidation = false;
// Realiza las inicializaciones de la instancia de la clase Page que requieran los diseñadores RAD.
page.DesignerInitialize();
page.Controls.Add(form);
form.Controls.Add(gv);
page.RenderControl(htw);
string style = @"<style> .text { mso-number-format:\@; } </script> ";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName + ".xls");
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");
// HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.Write(style);
HttpContext.Current.Response.End();
}
会出现00001变为1的情况,有如下修改方法
/// <summary>
/// gridView的绑定事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//比如身份证是第7列,格式化为文本。
e.Row.Cells[4].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
}
}
这种方法时在呈现gridView时,在数字类型的列中添加vnd.ms-excel.numberformat:@,使其成为text类型。
写下来作为记录