你的位置:首页 > ASP.net教程

[ASP.net教程]Asp.net导出Excel文件


  /// <summary>  /// 把DataTable内容导出excel并返回客户端   /// </summary>  /// <param name="header">标题行</param>  /// <param name="fileName">文件名称</param>  public void DataTable2Excel(TableCell[] header, string fileName)  {    // IO用于导出并返回excel文件     var strWriter = new StringWriter();    var htmlWriter = new HtmlTextWriter(strWriter);    // 设置编码和附件格式     Response.ContentType = "application/ms-excel";    Response.ContentEncoding = Encoding.GetEncoding("gb2312");    Response.Charset = "gb2312";    if (!string.IsNullOrEmpty(fileName))    {      //处理中文名乱码问题       fileName = HttpUtility.UrlEncode(fileName, Encoding.UTF8);      Response.AppendHeader("Content-Disposition", ("attachment;filename=" + (fileName.ToLower().EndsWith(".xls") ? fileName : fileName + ".xls")));    }    Response.Flush();    var gvExport = new GridView();// 重新定义一个无分页的GridView     var postData = string.Format("&partner={0}&pageIndex=1&pageSize=1000&userId=", Partner);    var dt = new DataTable();//这里是要导出的数据    gvExport.DataSource = dt.DefaultView;    gvExport.AllowPaging = false;    gvExport.RowDataBound += dgExport_RowDataBound; //优化导出数据显示,如身份证、12-1等显示异常问题    gvExport.DataBind();    if (header != null && header.Length > 0)//处理表头    {      gvExport.HeaderRow.Cells.Clear();      gvExport.HeaderRow.Cells.AddRange(header);    }    gvExport.RenderControl(htmlWriter);// 返回客户端     Response.Write(strWriter);    Response.End();  }