ASP.NET导出数据到Excel实现程序

一、定义文档类型、字符编码

 代码如下 复制代码
   Response.Clear();
   Response.Buffer= true;
   Response.Charset="utf-8";  
   //下面这行很重要, attachment 参数表示作为附件下载,您可以改成 online在线打开
   //filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc    .xls    .txt   .htm  
   Response.AppendHeader("Content-Disposition","attachment;filename=FileFlow.xls");
   Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");  
//Response.ContentType指定文件类型 可以为application/ms-excel application/ms-word    application/ms-txt    application/ms-html 或其他浏览器可直接支持文档 
   Response.ContentType = "application/ms-excel";
   this.EnableViewState = false;  

 
二、定义一个输入流  

 代码如下 复制代码
   system.IO.StringWriter oStringWriter = new system.IO.StringWriter();
   system.Web.UI.HtmlTextWriter oHtmlTextWriter = new system.Web.UI.HtmlTextWriter(oStringWriter);

三、将目标数据绑定到输入流输出  

 代码如下 复制代码
   this.RenderControl(oHtmlTextWriter);
   //this 表示输出本页,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件  
   Response.Write(oStringWriter.ToString());
   Response.End();

四、 这时如果发生"只能在执行 Render() 的过程中调用 RegisterForEventValidation"的错误提示。

有两种方法可以解决:
 
1.修改web.config(不推荐)<pages enableEventValidation ="false" ></pages>
2.直接在导出Execl的页面修改 

好了说了一大堆放了,下面我们来看利用.net的类型“GridView”的控件“ctl00_center_GridView1”必须放在具有 runat=server 的窗体标记内。 说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 异常详细信息:System.Web.HttpException: 类型“GridView”的控件“ctl00_center_GridView1”必须放在具有 runat=server 的窗体标记内。

这段错误描述是我在注释了这段程序是报的错,

 代码如下 复制代码

//publicoverridevoidVerifyRenderingInServerForm(Controlcontrol)
//{
//  //base.VerifyRenderingInServerForm(control);
//}

  虽然这个方法里的内容也被注释了,也就是说这是个空方法,但是如果没有个方法,程序就会报上面那个错误。最初见到这段错误说明是想到了以前做ajax程序时报的一个错误很是类似。同样是因为没有重写VerifyRenderingInServerForm方法所致。在此提醒使用的朋友注意,下面贴出导出到Excel的代码

 

 代码如下 复制代码
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Collections;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
usingSystem.IO;
///<summary>
///ToExcleHelper的摘要说明
///</summary>
  publicclassExportHelper
  {
    publicstaticvoidExportToExcel(IListdataList,string[]fields,string[]headTexts,stringtitle)
    {
      GridViewgvw=newGridView();
      intColCount,i;
      //如果筛选的字段和对应的列头名称个数相对的情况下只导出指定的字段
      if(fields.Length!=0&&fields.Length==headTexts.Length)
      {
        ColCount=fields.Length;
        gvw.AutoGenerateColumns=false;
        for(i=0;i<ColCount;i++)
        {
          BoundFieldbf=newBoundField();
          bf.DataField=fields[i];
          bf.HeaderText=headTexts[i];
          gvw.Columns.Add(bf);
        }
      }
      else
      {
        gvw.AutoGenerateColumns=true;
      }
      SetStype(gvw);
      gvw.DataSource=dataList;
      gvw.DataBind();
      ExportToExcel(gvw,title);
    }
    ///<summary>
    ///导出数据到Excel
    ///</summary>
    ///<paramname="DataList">IListData</param>
    ///<paramname="Fields">要导出的字段</param>
    ///<paramname="HeadName">字段对应显示的名称</param>
    publicstaticvoidExportToExcel(IListdataList,string[]fields,string[]headTexts)
    {
      ExportToExcel(dataList,fields,headTexts,string.Empty);
    }
    ///<summary>
    ///设置样式
    ///</summary>
    ///<paramname="gvw"></param>
    privatestaticvoidSetStype(GridViewgvw)
    {
      gvw.Font.Name="Verdana";
      gvw.BorderStyle=System.Web.UI.WebControls.BorderStyle.Solid;
      gvw.HeaderStyle.BackColor=System.Drawing.Color.LightCyan;
      gvw.HeaderStyle.ForeColor=System.Drawing.Color.Black;
      gvw.HeaderStyle.HorizontalAlign=System.Web.UI.WebControls.HorizontalAlign.Center;
      gvw.HeaderStyle.Wrap=false;
      gvw.HeaderStyle.Font.Bold=true;
      gvw.HeaderStyle.Font.Size=10;
      gvw.RowStyle.Font.Size=10;
    }
    ///<summary>
    ///导出GridView中的数据到Excel
    ///</summary>
    ///<paramname="gvw"></param>
    ///<paramname="DataList"></param>
    publicstaticvoidExportToExcel(GridViewgvw,stringtitle)
    {
      stringfileName;
      HttpContext.Current.Response.Buffer=true;
      HttpContext.Current.Response.ClearContent();
      HttpContext.Current.Response.ClearHeaders();
      fileName=string.Format("xhmd{0:yyMMddHHmm}.xls",DateTime.Now);
      HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+fileName);
      HttpContext.Current.Response.ContentType="application/vnd.ms-excel";
      StringWritertw=newSystem.IO.StringWriter();
      HtmlTextWriterhw=newSystem.Web.UI.HtmlTextWriter(tw);
      gvw.RenderControl(hw);
      if(!string.IsNullOrEmpty(title))
      {
        HttpContext.Current.Response.Write("<b><center><fontsize=3face=Verdanacolor=#0000FF>"+title+"</font></center></b>");
      }
      HttpContext.Current.Response.Write(tw.ToString());
      HttpContext.Current.Response.Flush();
      HttpContext.Current.Response.Close();
      HttpContext.Current.Response.End();
      gvw.Dispose();
      tw.Dispose();
      hw.Dispose();
      gvw=null;
      tw=null;
      hw=null;
    }
    publicstaticvoidDataTable2Excel(System.Data.DataTabledtData)
    {
      System.Web.UI.WebControls.DataGriddgExport=null;
     //当前对话
      System.Web.HttpContextcurContext=System.Web.HttpContext.Current;
      //IO用于导出并返回excel文件
      System.IO.StringWriterstrWriter=null;
      System.Web.UI.HtmlTextWriterhtmlWriter=null;
      if(dtData!=null)
     {
        //设置编码和附件格式
       curContext.Response.ContentType="application/vnd.ms-excel";
       curContext.Response.ContentEncoding=System.Text.Encoding.UTF8;
       curContext.Response.Charset="";
        
        //导出excel文件
       strWriter=newSystem.IO.StringWriter();
       htmlWriter=newSystem.Web.UI.HtmlTextWriter(strWriter);
       //为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid
        dgExport=newSystem.Web.UI.WebControls.DataGrid();
        dgExport.DataSource=dtData.DefaultView;
        dgExport.AllowPaging=false;
        dgExport.DataBind();
        //返回客户端
        dgExport.RenderControl(htmlWriter);  
        curContext.Response.Write(strWriter.ToString());
        curContext.Response.End();
      }
    }
  }

总结,最后这个带了可以操作分页导出的,相对文章开始来说是复杂了许多哦。

时间: 2024-08-17 21:33:46

ASP.NET导出数据到Excel实现程序的相关文章

ASP.NET导出数据到Excel的实现方法

在做asp.net程序时涉及到数据显示的时候多数会要求打印,而网页上的打印格式往往又不能满足需求,经常用的方法就是导入到Excel以后再进行打印.(仿佛这已经是老生常谈)今天在网上搜了一段打印的代码,觉得不错,需要打印的朋友可以看看.   网上好些代码的原理大致与此类似,同样都存在一个问题,就是: 类型"GridView"的控件 "ctl00_center_GridView1"必须放在具有 runat=server 的窗体标记内. 说明: 执行当前 Web 请求期间

ASP.NET导出数据到Excel并输出

asp教程.net导出数据到excel并输出 public void import()     {         if (this.ddl_task.selectedvalue == "-1")         {             function.script.alert("请选择主题!");             return;         }         string savepath = server.mappath("sql\

ASP.NET导出数据到Excel的实现方法_实用技巧

网上好些代码的原理大致与此类似,同样都存在一个问题,就是: 类型"GridView"的控件"ctl00_center_GridView1"必须放在具有 runat=server 的窗体标记内. 说明: 执行当前 Web 请求期间,出现未处理的异常.请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息. 异常详细信息:System.Web.HttpException: 类型"GridView"的控件"ctl00_cent

ASP.NET导出数据到Excel

asp.net|excel|导出数据 该方法只是把asp.net页面保存成html页面只是把后缀改为xlc不过excel可以读取,接下连我看看还有别的方式能导出数据,并利用模版生成. 下面是代码 县新建一个asp.ne的tweb应用程序把代码粘贴进去就好了 html页面代码 <%@ Page language="c#" Codebehind="OutExcel.aspx.cs" AutoEventWireup="false" Inherit

ASP如何导出数据到Excel表

<% Rem 初始化ExcelApplication的工作环境 Dim ExcelApp,eBook,eSheet Set ExcelApp = CreateObject("Excel.Application") '建立Excel对象 ExcelApp.DisplayAlerts=false '不显示警告 ExcelApp.Application.Visible=false '不显示界面 Rem 初始化Excel数据 'ExcelApp.Workbooks.Open(Server

asp.net导出数据到excel方法

 代码如下 复制代码 public static void TableToExcel(System.Data.DataTable dt, string fileType)   {   System.IO.StringWriter sw = new System.IO.StringWriter();   System.Text.StringBuilder sb = new System.Text.StringBuilder();   if (fileType.Equals("xls"))

[Asp.net]常见数据导入Excel,Excel数据导入数据库解决方案,总有一款适合你!

原文:[Asp.net]常见数据导入Excel,Excel数据导入数据库解决方案,总有一款适合你! 引言 项目中常用到将数据导入Excel,将Excel中的数据导入数据库的功能,曾经也查找过相关的内容,将曾经用过的方案总结一下. 方案一 NPOI NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目.使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写.NPOI是构建在

excel-C# 导出数据到EXCEL 小数位出错

问题描述 C# 导出数据到EXCEL 小数位出错 EXcel 数据表中的数据14.40,导入C#中,通过DateGridView显示,再把DateGridView中的数据14.40导出到Excel中,数据就变成了14.39999919?????? 程序: Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得

vs2012-从datagrid导出数据到excel中出现错误

问题描述 从datagrid导出数据到excel中出现错误 private void button2_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Excel files (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.Rest