Beyond the dream——飛雪飄寒

————磨難不過是人生鍵盤的回車。。。。。。
  博客园  :: 首页  :: 联系 :: 订阅 订阅  :: 管理

.net实现导出Word、Excel格式文件

Posted on 2008-06-13 16:31  飛雪飄寒  阅读(7416)  评论(11编辑  收藏  举报
    在做.NET项目时,会经常遇到要导出文件的问题,如将DataGrid中的数据导出到excel、word文件等,经常使用的是Office中的OWC组件,这个组件提供的功能很强大,在一般的项目中都可以满足当前的需要.但是这个功能强大的组件使用起来却不是很方便,不但有版本的问题,而且代码量也相对比较大.现在简单介绍一下利用Respone对象和相关的IO实现导出excel/word等文件的方法。

    1.Respone对象及相关的IO介绍
    System.IO.StringWriter SW = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter HTW=new System.Web.UI.HtmlTextWriter(SW);
    Page.RenderControl(HTW);
    //Page为要导出的对象,当前是Page,如果是DataGrid,DataList等都可以
    Response.Buffer=true;
    Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    Response.ContentType = "Response.ContentType";
    //Response.ContentType是输出流的 HTTP MIME 类型
    //Response.ContentType      --- word文件
    //application/vnd.ms-excel --- excel文件
    Response.Charset="utf-8";
    Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");
    Response.AddHeader("Content-Disposition", "attachment;filename=XXX.doc");
    //attachment --- 作为附件下载
    //inline --- 在线打开
    //filename如过是中文,则可以用HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8)进行编码,以解决文件名乱码的问题
    Response.Write(SW.ToString());
    Response.Flush();
    Response.Close();  

    2.实现方法
    列出.net实现导出Word、Exce格式文件调用的具体方法,代码如下:
    
        /// <summary>
        
/// 将Web控件导出
        
/// </summary>
        
/// <param name="source">控件实例</param>
        
/// <param name="type">类型:Excel或Word</param>

        public void ExpertControl(System.Web.UI.Control source, DocumentType type)
        
{
            
//设置Http的头信息,编码格式
            if (type == DocumentType.Excel)
            
{
                
//Excel
                Response.AppendHeader("Content-Disposition","attachment;filename=result.xls");
                Response.ContentType 
= "application/ms-excel";
            }

            
else if (type == DocumentType.Word)
            
{
                
//Word
                Response.AppendHeader("Content-Disposition","attachment;filename=result.doc");
                Response.ContentType 
= "application/ms-word";
            }

            Response.Charset 
= "UTF-8";  
            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); 

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


        
//文档类型
        public enum DocumentType
        
{
            Word,
            Excel
        }
    调用方法:
    ExpertControl(this, DocumentType.Word);
    这是将整个页面导出为Word
    //this可以为具体的控件如datagrid/dataList或page表示当前页,DocumentType为导出的文件格式(Excel/word)
    注意:当为datagrid或dataList控件时,在导出Excel/word文件时,必须把控件的分页、排序属性去除并重新绑定,否则将出现
"类型“DataGridLinkButton”的控件“DataGrid1__ctl14__ctl1”必须放在具有 runat=server 的窗体标记内。"错误!
    
    3.具体实例
    为了让大家具体理解.net实现导出Word、Exce格式文件功能,下面贴出一个具体实例代码以供参考! 
    前台代码    
<%@ Page language="c#" Codebehind="InSum.aspx.cs" AutoEventWireup="false" Inherits="FLX.Portal.InSum" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    
<HEAD>
        
<title>InSum</title>
        
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
        
<meta name="CODE_LANGUAGE" Content="C#">
        
<meta name="vs_defaultClientScript" content="JavaScript">
        
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    
</HEAD>
    
<body>
        
<form id="Form1" method="post" runat="server">
            
<P>
                
<asp:Label id="Label1" runat="server" Font-Size="14px" Font-Bold="True">输出形式:</asp:Label>
                
<asp:DropDownList id="DDLOutPut" runat="server">
                    
<asp:ListItem Value="Excel">Excel</asp:ListItem>
                    
<asp:ListItem Value="Word">Word</asp:ListItem>
                
</asp:DropDownList>
                
<asp:Button id="BtnOutPut" runat="server" Text="导出文件"></asp:Button>
                
<asp:datagrid id="DataGrid1" runat="server" AutoGenerateColumns="False" Width="100%" BorderColor="#CCCCCC"
                    BorderStyle
="None" BorderWidth="1px" BackColor="White" CellPadding="3" AllowPaging="True"
                    Font
-Size="12px" ShowFooter="True">
                    
<FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>
                    
<SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#669999"></SelectedItemStyle>
                    
<ItemStyle ForeColor="#000066" BorderColor="#D4D0C8"></ItemStyle>
                    
<HeaderStyle ForeColor="Black" BackColor="#E1EEFE"></HeaderStyle>
                    
<Columns>
                        
<asp:BoundColumn DataField="id" HeaderText="id"></asp:BoundColumn>
                        
<asp:BoundColumn DataField="count1" HeaderText="count1"></asp:BoundColumn>
                        
<asp:BoundColumn DataField="count2" HeaderText="count2"></asp:BoundColumn>
                        
<asp:TemplateColumn HeaderText="count3">
                            
<ItemTemplate>
                                
<asp:Label id=lblQuantity runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.count3") %>'>
                                
</asp:Label>
                            
</ItemTemplate>
                        
</asp:TemplateColumn>
                    
</Columns>
                    
<PagerStyle HorizontalAlign="Left" ForeColor="#000066" BackColor="White" Mode="NumericPages"></PagerStyle>
                
</asp:datagrid></P>
        
</form>
    
</body>
</HTML>
    后台代码    
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using FLX.Configuration;
using System.Text;

namespace FLX.Portal
{
    
/// <summary>
    
/// InSum 的摘要说明。
    
/// </summary>

    public class InSum : PortalPagePersonal
    
{
        
public int intSum1=0;
        
public int intSum2=0;
        
public int intSum3=0;
        
protected System.Web.UI.WebControls.Button BtnOutPut;
        
protected System.Web.UI.WebControls.Label Label1;
        
protected System.Web.UI.WebControls.DropDownList DDLOutPut;
        
protected System.Web.UI.WebControls.DataGrid DataGrid1;
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
// 在此处放置用户代码以初始化页面
            if(!this.IsPostBack)
            
{
                
this.DataGrid1.DataSource =this.GetDataBind();
                
this.DataGrid1 .DataBind();
            }

        }


        
Web 窗体设计器生成的代码

        
private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        
{
            
if(e.Item.ItemIndex >= 0)
            
{
                
//取指定列的数据总和
                intSum1 += int.Parse(e.Item.Cells[1].Text.ToString());
                intSum2 
+= int.Parse(e.Item.Cells[2].Text.ToString());
                Label lblQuantity 
= (Label)e.Item.Cells[3].FindControl("lblQuantity"); 
                intSum3 
+= int.Parse(lblQuantity.Text.ToString());
            }

            
else if(e.Item.ItemType == ListItemType.Footer)
            
{
                e.Item.Cells[
0].Text = "<font color='red'>总计:</font>";   
                e.Item.Cells[
1].Text = "<font color='red'>"+intSum1.ToString()+"</font>"; 
                e.Item.Cells[
2].Text = "<font color='red'>"+intSum2.ToString()+"</font>"; 
                e.Item.Cells[
3].Text = "<font color='red'>"+intSum3.ToString()+"</font>"; 
            }

        }

        
private DataTable GetDataBind()
        
{
            
string sql="select * from Count";
            DataTable dt
=new DataTable();
            dt
=this.DataAccessFacade.ExecuteDataTable(sql);
            
return dt;
        }


        
private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        
{
            
if(e.Item.ItemType==ListItemType.Header)
            
{
                TableCellCollection tcl
=e.Item.Cells;
                tcl.Clear();
                tcl.Add(
new TableHeaderCell());
                tcl[
0].ColumnSpan =4;                
                tcl[
0].Text="第一季度个人消费情况表</th></tr><tr><td rowspan =\"2\">姓名</td><td colspan=\"3\" align=\"center\">帐目统计</td></tr><tr><td>项目一</td><td>项目二</td><td>项目三</td>";            
            }

        }


        
private void BtnOutPut_Click(object sender, System.EventArgs e)
        
{
            
if(this.DDLOutPut.SelectedItem.Text =="Excel")
            
{
                
this.DataGrid1.AllowPaging =false;
                
this.DataGrid1.DataSource =this.GetDataBind();
                
this.DataGrid1 .DataBind();
                ExpertControl(
this, DocumentType.Excel);
                
this.DataGrid1.AllowPaging =true;
                
this.DataGrid1.DataSource =this.GetDataBind();
                
this.DataGrid1 .DataBind();
            }

            
else
            
{
                
this.DataGrid1.AllowPaging =false;
                
this.DataGrid1.DataSource =this.GetDataBind();
                
this.DataGrid1 .DataBind();
                ExpertControl(
this, DocumentType.Word);
                
this.DataGrid1.AllowPaging =true;
                
this.DataGrid1.DataSource =this.GetDataBind();
                
this.DataGrid1 .DataBind();
            }
    
        }


        
/// <summary>
        
/// 将Web控件导出
        
/// </summary>
        
/// <param name="source">控件实例</param>
        
/// <param name="type">类型:Excel或Word</param>

        public void ExpertControl(System.Web.UI.Control source, DocumentType type)
        
{
            
//设置Http的头信息,编码格式
            if (type == DocumentType.Excel)
            
{
                
//Excel
                Response.AppendHeader("Content-Disposition","attachment;filename=result.xls");
                Response.ContentType 
= "application/ms-excel";
            }

            
else if (type == DocumentType.Word)
            
{
                
//Word
                Response.AppendHeader("Content-Disposition","attachment;filename=result.doc");
                Response.ContentType 
= "application/ms-word";
            }

            Response.Charset 
= "UTF-8";  
            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); 

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

        
private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
        
{
            
this.DataGrid1.CurrentPageIndex =e.NewPageIndex ;
            
this.DataGrid1.DataSource =this.GetDataBind();
            
this.DataGrid1.DataBind();
        }
 

        
//文档类型
        public enum DocumentType
        
{
            Word,
            Excel
        }
 
    }

}
    效果展示
    1.导出Excel文件

    2.导出Word文件