首页 > 网站 > 建站经验 > 正文

ASP.NET(C#)将数、据导出到Word或Excel

2019-11-02 14:19:06
字体:
来源:转载
供稿:网友

   最简单的方法是把页面上所有的东西都导出

  在载入时调用,注意页面里不能有其它控件,包括按钮

  void converttoexcel()

  {

  Response.Clear();

  Response.Buffer = true;

  Response.Charset = "GB2312";

  Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls");

  Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

  Response.ContentType = "application/ms-excel";

  this.Page.EnableViewState = false;

  System.IO.StringWriter oStringWriter = new System.IO.StringWriter();

  System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

  this.Page.RenderControl(oHtmlTextWriter);

  Response.Write(oStringWriter.ToString());

  Response.End();

  }

  ASP.NET(C#)将数据导出到WordExcel

  命名空间:

  using System.IO;

  using System.Text;

  将DataGrid的数据导出到Excel

  string excelname="excel文件名";

  HttpContext.Current.Response.Charset = "GB2312";

  HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;

  HttpContext.Current.Response.ContentType = "application/ms-excel";

  HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment;filename=" + excelname + ".xls");

  dr1.Page.EnableViewState = false;

  StringWriter sw = new StringWriter();

  HtmlTextWriter tw = new HtmlTextWriter(sw);

  dr1.RenderControl(tw);

  HttpContext.Current.Response.Write(sw.ToString());

  HttpContext.Current.Response.End();

  将DataGrid的数据导出到Word

  string excelname="word文件名";

  HttpContext.Current.Response.Charset = "GB2312";

  HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;

  HttpContext.Current.Response.ContentType = "application/ms-winword";

  HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment;filename=" + excelname + ".doc");

  dr1.Page.EnableViewState = false;

  StringWriter sw = new StringWriter();

  HtmlTextWriter tw = new HtmlTextWriter(sw);

  dr1.RenderControl(tw);

  HttpContext.Current.Response.Write(sw.ToString());

  HttpContext.Current.Response.End();

  ASP.NET 2.0,C#----利用GridView控件导出其他文件(导出Excel,导出Word文件)

  // 注意,在Visual Studio2005平台下,如果使用GridView导出文件,

  //就必须重载VerifyRenderingInServerForm方法

  public override void VerifyRenderingInServerForm(Control control)

  {

  }

  ///

  /// 导出到文件的方法,

  ///

  /// Model=1:导出为Execl,Model=2:导出为Word

  private void toFiles(int Model)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表