Asp.net网页中DataGridView数据导出到Excel

2013 年 8 月 9 日4080

一、从DataGridView中直接导出数据到Excel文件

  经过上网找资料,终于找到一种可以直接将GridView中数据导出到Excel文件的方法,归纳方法如下:

  1、 注:其中的字符集格式若改为"GB2312",导出的部分数据可能为乱码;

  导出之前需要关闭分页部分,若分页只导出首页的数据;

  ///

  /// 下载数据

  ///

  ///文件类型

  ///Excel表名

  private void Excel(string FileType, string FileName)

  {

  try

  {

  Response.Clear();

  Response.Buffer = true;

  Response.Charset = "utf-8";

  //返回与指定代码页关联的数据

  Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");

  //attachment表示作为附件下载,filename指定输出文件名称

  Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());

  //指定文件类型

  Response.ContentType = FileType;

  this.EnableViewState = false;

  System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);

  //定义一输入流

  StringWriter tw = new StringWriter(myCItrad);

  HtmlTextWriter hw = new HtmlTextWriter(tw);

  this.gvJstList.RenderControl(hw);

  Response.Write(tw.ToString());

  Response.End();

  }

  catch (Exception err)

  {

  ScriptManager.RegisterStartupScript(this, this.GetType(), "js", "showInfo('ctl00_Contentplaceholder2_ValidationSummary1',1,'发生错误:" + err.Message.Replace("rn", "\r\n").Replace("'", "'") + "')", true);

  return;

  }

  }

  如上代码如果处理一般的GridView导出应该是没有问题的,但是如果GridView的AutoGenerateDeleteButton,AutoGenerateEditButton,AutoGenerateSelectButton有的设置为True了,或者GridView中有HyperLinkField类型的字段,那么就会抛出形如"类型"GridView"的控件"XXXX"必须放在具有 runat=server 的窗体标记内."的异常!

  那么他的解决方案是:对WebForm窗体的VerifyRenderingInServerForm方法进行Override!

  代码如下:

  public override void VerifyRenderingInServerForm(Control control)

  {

  //OverRide 为了使导出成Excel可行!

  }

 2、/*如导出的表中有某些列为编号、身份证号之类的纯数字字符串,如不进行处理,则导出的数据会默认为数字,例如原字符串"0010"则会变为数字10,字符串"1245787888"则会变为科学计数法1.236+E9,这样便达不到我们想要的结果,所以需要在导出前对相应列添加格式化的数据类型,以下为格式化为字符串型*/

  在上面的代码中添加以下代码:

  foreach (GridViewRow dg in this.gridview1.Rows)

  {

  dg.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");

  dg.Cells[5].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");

  dg.Cells[6].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");

  dg.Cells[8].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");

  }

  或者是在DataGridView事件RowDataBound中添加以下代码:

  if(e.Row.RowType == DataControlRowType.DataRow )

  {

  e.Row.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:@");

  e.Row.Cells[4].Attributes.Add("style", "vnd.ms-excel.numberformat:@");

  }

本文关键词:Asp.net,网页,DataGridView,Excel

0 0