.net导出Excle和Word的方法(一)

在导出Excle否者是Word时,我在网上搜集到有两种方法,其中一种是可以导出页面控件的方法(我认为是比较简单的方法),代码如下:

 .aspx页面代码:

 ContractedBlock.gifCode                                                             

ExpandedBlockStart.gif
<%@ Page Language="C#"  EnableEventValidation = "false"  AutoEventWireup="true"   CodeFile="Default.aspx.cs" Inherits="_Default" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>导出数据的页面</title>
</head>
<body style="text-align: center">
    
<form id="form1" runat="server">
    
<div align="left" runat="server" >
        
<asp:GridView ID="gvShow" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvShow_RowDataBound"
            ShowFooter
="True" AllowPaging="True" PageSize="5"  OnPageIndexChanging="gvShow_PageIndexChanging">
            
<Columns>
                
<asp:BoundField DataField="id" HeaderText="ID" />
                
<asp:BoundField DataField="name" HeaderText="种类" />
                
<asp:BoundField DataField="number" HeaderText="个数" />
                
<asp:BoundField DataField="je" HeaderText="金额" />
            
</Columns>
        
</asp:GridView>
        
<br />
        
<asp:Button ID="btnOut" runat="server"  Text="导出数据" OnClick="btnOut_Click" />
    
</div>
    
</form>
</body>
</html>

后台.aspx.cs代码:

ContractedBlock.gif ExpandedBlockStart.gif 后台代码(借鉴了 博友彭建军的方法
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
ExpandedBlockStart.gifContractedBlock.gif
{
ContractedSubBlock.gifExpandedSubBlockStart.gif    
属性#region 属性
    
private int sum1 = 0;
    
private double sum2 = 0;
    
#endregion

    
protected void Page_Load(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
if(!IsPostBack)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
this.bindtopinfo();
        }

    }

ContractedSubBlock.gifExpandedSubBlockStart.gif    
加载数据#region 加载数据
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
    
/// 绑定GridView
    
/// </summary>

    private void bindtopinfo()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
string strConn = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
        SqlConnection conn 
= new SqlConnection(strConn);
        
if (conn.State.Equals(ConnectionState.Closed))
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            conn.Open();
        }

        SqlDataAdapter sda 
= new SqlDataAdapter();
        sda.SelectCommand 
= new SqlCommand("select * from PInfo", conn);
        DataSet ds 
= new DataSet();
        sda.Fill(ds, 
"PInfo");
        
this.gvShow.DataSource = ds.Tables["PInfo"];
        
this.gvShow.DataBind();
    }

    
protected void gvShow_RowDataBound(object sender, GridViewRowEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
if (e.Row.RowType == DataControlRowType.DataRow)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
if (e.Row.Cells[2].Text != null || e.Row.Cells[2].Text != "")
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                sum1 
+= Convert.ToInt32(e.Row.Cells[2].Text);
                sum2 
+= Convert.ToInt32(e.Row.Cells[3].Text);
            }

        }

        
else if (e.Row.RowType == DataControlRowType.Footer)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            e.Row.Cells[
0].Text = "合计:";
            e.Row.Cells[
2].Text = "合计:" + sum1;
            e.Row.Cells[
3].Text = "合计:" + sum2;
        }

    }

    
protected void gvShow_PageIndexChanging(object sender, GridViewPageEventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
this.gvShow.PageIndex = e.NewPageIndex;
        
this.bindtopinfo();
    }


    
#endregion
 

ContractedSubBlock.gifExpandedSubBlockStart.gif    
导出页面或web控件方法#region 导出页面或web控件方法
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
    
/// 将Web控件或页面信息导出(不带文件名参数)
    
/// </summary>
    
/// <param name="source">控件实例</param>        
    
/// <param name="DocumentType">导出类型:Excel或Word</param>

    public void ExportControl(System.Web.UI.Control source, string DocumentType)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
//设置Http的头信息,编码格式
        if (DocumentType == "Excel")
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//Excel            
            HttpContext.Current.Response.AppendHeader("Content-Disposition""attachment;filename=" + HttpUtility.UrlEncode("下载文件.xls", System.Text.Encoding.UTF8));
            HttpContext.Current.Response.ContentType 
= "application/ms-excel";
        }


        
else if (DocumentType == "Word")
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//Word
            HttpContext.Current.Response.AppendHeader("Content-Disposition""attachment;filename=" + HttpUtility.UrlEncode("下载文件.doc", System.Text.Encoding.UTF8));
            HttpContext.Current.Response.ContentType 
= "application/ms-word";
        }

        HttpContext.Current.Response.Charset 
= "UTF-8";
        HttpContext.Current.Response.ContentEncoding 
= System.Text.Encoding.UTF8;

        
//关闭控件的视图状态
        source.Page.EnableViewState = false;

        
//初始化HtmlWriter
        System.IO.StringWriter writer = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWriter 
= new System.Web.UI.HtmlTextWriter(writer);
        source.RenderControl(htmlWriter);

        
//输出
        HttpContext.Current.Response.Write(writer.ToString());
        HttpContext.Current.Response.End();
    }

ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
    
/// 将Web控件或页面信息导出(带文件名参数)
    
/// </summary>
    
/// <param name="source">控件实例</param>        
    
/// <param name="DocumentType">导出类型:Excel或Word</param>
    
/// <param name="filename">保存文件名</param>

    public void ExportControl(System.Web.UI.Control source, string DocumentType, string filename)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
//设置Http的头信息,编码格式
        if (DocumentType == "Excel")
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//Excel            
            HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+ HttpUtility.UrlEncode(filename+".xls",System.Text.Encoding.UTF8));
            HttpContext.Current.Response.ContentType 
= "application/ms-excel";            
        }


        
else if (DocumentType == "Word")
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
//Word
            HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+ HttpUtility.UrlEncode(filename+".doc",System.Text.Encoding.UTF8));
            HttpContext.Current.Response.ContentType 
= "application/ms-word";
        }


        HttpContext.Current.Response.Charset 
= "UTF-8";   
        HttpContext.Current.Response.ContentEncoding 
= System.Text.Encoding.UTF8; 

        
//关闭控件的视图状态
        source.Page.EnableViewState =false;    

        
//初始化HtmlWriter
        System.IO.StringWriter writer = new System.IO.StringWriter() ;
        System.Web.UI.HtmlTextWriter htmlWriter 
= new System.Web.UI.HtmlTextWriter(writer);
        source.RenderControl(htmlWriter); 

        
//输出
        HttpContext.Current.Response.Write(writer.ToString());
        HttpContext.Current.Response.End();
    }

    
#endregion


ContractedSubBlock.gifExpandedSubBlockStart.gif    
导出GridView中的数据#region 导出GridView中的数据
    
    
public override void VerifyRenderingInServerForm(Control control)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
// Confirms that an HtmlForm control is rendered for
    }

    
protected void btnOut_Click(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
this.gvShow.AllowPaging = false;
        
this.bindtopinfo();
        ExportControl(
this.gvShow, "Excel""testfilename");
        
this.gvShow.AllowPaging = true;
    }

    
#endregion

}

 

这里有一个地方,就是在后台要加上

public override void VerifyRenderingInServerForm(Control control)

    {
        // Confirms that an HtmlForm control is rendered for

    }

 

为什么呢?如果不加上就会出现这样的错误:控件“GridView”必须放在具有 runat=server 的窗体标记内。

 MSDN对该方法的解释如下:

必须位于 <form runat=server> 标记中的控件可以在呈现之前调用此方法,以便在控件被置于标记外时显示错误信息。发送回或依赖于注册的脚本块的控件应该在 Control.Render 方法的重写中调用此方法。呈现服务器窗体元素的方式不同的页可以重写此方法以在不同的条件下引发异常。

如果回发或使用客户端脚本的服务器控件没有包含在 HtmlForm 服务器控件 ( <form runat="server">) 标记中,它们将无法正常工作。这些控件可以在呈现时调用该方法,以在它们没有包含在 HtmlForm 控件中时提供明确的错误信息。

开发自定义服务器控件时,通常在为任何类型的输入标记重写 Render 方法时调用该方法。这在输入控件调用 GetPostBackEventReference 或发出客户端脚本时尤其重要。复合服务器控件不需要作出此调用。

 

 

转载于:https://www.cnblogs.com/yinhe/archive/2008/10/31/1323972.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值