來自於:http://csharp.banzhu.net/article/csharp-2-74809.html
在做.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格式文件調用的具體方法,代碼如下:
/// 將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格式文件功能,下面貼出一個具體實例代碼以供參考!
前臺代碼
<!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.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();
}
}
#region Web 窗體設計器生成的代碼
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 該調用是 ASP.NET Web 窗體設計器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 設計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void InitializeComponent()
{
this.BtnOutPut.Click += new System.EventHandler(this.BtnOutPut_Click);
this.DataGrid1.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemCreated);
this.DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);
this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
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文件