`

一键导出Word和Excel文件的简单服务器控件

阅读更多

http://blog.joycode.com/mmkk/archive/2004/09/21/34105.aspx

出于项目的需求,写了这样一个控件,使用起来很简单,只需要3句代码:

exportExcel.FileType = TSCRMLiteWeb.SC.ExportFileType.Excel;
exportExcel.ExportFileName = "currencyList";
exportExcel.TargetControlID = "currencyContianer.gridCurrencyList";

需要说明的只有几点:

1.由于项目中所有需要导出内容的控件都是DataGrid,因此只针对对此控件的测试,满足需求先,其它就没有测试过了:)

2.属性ExportFileName不要扩展名,FileType属性指定以后,控件自身就会得到对应的扩展名了

3.最关键的地方就是TargetControlID,这是需要导出内容的服务器控件的“路径“,通常是DataGrid的ID值,如果你的DataGrid就直接在Page下面,那么TargetControlID的值就直接设为DataGrid的ID,如果DataGrid父亲控件不是Page,那么一直追朔到Page下的一级控件,比如上面的例子,currencyContainer就是一个Page下面的控件,gridCurrencyList的父亲控件是currencyContainer,他们之间用点号分开,看过代码后你就会知道是为什么了,就这些。这里是所有的代码:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TSCRMLiteWeb.SC
{
/// <summary>
/// 导出Excel,Word等Office文件的LinkButton服务器控件
/// </summary>
public class ExportButton : LinkButton
{
public ExportButton()
{
//
// TODO: 在此处添加构造函数逻辑
//
}

protected override void OnClick(EventArgs e)
{
ExportButton_Click();
}
/// <summary>
/// 扩展名,在设置导出文件类型的时候同时设置
/// </summary>
private string ExtensionType
{
get
{
if(ViewState["ExtensionType"] == null)
return ".xls";
return (string)ViewState["ExtensionType"];
}
set
{
ViewState["ExtensionType"] = value;
}
}

/// <summary>
/// 要导出内容的目标控件ID,如果目标控件的父亲控件不是Page,那么应该从Page下的该控件的根控件开始传入,格式是ParentControlID.ControlID.ControlID...
/// </summary>
public string TargetControlID
{
get
{
if(ViewState["TargetControlID"] == null)
return String.Empty;
return (string)ViewState["TargetControlID"];
}
set
{
ViewState["TargetControlID"] = value;
}
}
/// <summary>
/// 文件类型
/// </summary>
public ExportFileType FileType
{
get
{
if(ViewState["ExportFileType"] == null)
return ExportFileType.Excel;
return (ExportFileType)ViewState["ExportFileType"];
}
set
{
ViewState["ExportFileType"] = value;
switch(value)
{
case ExportFileType.Excel:
this.ExtensionType = ".xls";
break;
case ExportFileType.Word:
this.ExtensionType = ".doc";
break;
default:
this.ExtensionType = ".xls";
break;
}
}
}
/// <summary>
/// 导出的文件名
/// </summary>
public string ExportFileName
{
get
{
if(ViewState["ExportFileName"] == null)
return "ExportFile";
return (string)ViewState["ExportFileName"];
}
set
{
ViewState["ExportFileName"] = value;
}
}
protected override void Render(HtmlTextWriter writer)
{
if(Page != null)
{
Page.VerifyRenderingInServerForm(this);
}
this.CausesValidation = false;
base.Render (writer);
}

private void ExportButton_Click()
{
//确保找到控件
Control c = AnalyseControlID();
if(c == null)
return;
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Buffer= true;
response.ContentType = SetContentType();
response.AddHeader("Content-Disposition", "attachment; filename=" + ExportFileName + ExtensionType + "");
response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
response.Charset = "gb2312";
EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
ClearControls(c);
c.RenderControl(oHtmlTextWriter);
response.Write(oStringWriter.ToString());
response.End();
//ClearControls(c);
}
private string SetContentType()
{
string contentType = String.Empty;
switch(FileType)
{
case ExportFileType.Excel:
contentType = "application/vnd.ms-excel";
break;
case ExportFileType.Word:
contentType = "application/vnd.ms-word";
break;
}
return contentType;
}
private Control AnalyseControlID()
{
if(Page != null)
{
string[] controlIDArray = TargetControlID.Split('.');
Control c = Page.FindControl(controlIDArray[0]);
// HttpContext.Current.Response.Write(controlIDArray.Length);
for(int i = 1;i < controlIDArray.Length;i++)
{
HttpContext.Current.Response.Write(controlIDArray[i]);
c = c.FindControl(controlIDArray[i]);
}

return c;
}
return null;
}
/// <summary>
/// 清除可能产生回发的子控件变成文本控件,如果不这样做的话,调用RenderControl会产生错误
/// Reference:http://www.c-sharpcorner.com/Code/2003/Sept/ExportASPNetDataGridToExcel.asp
/// </summary>
/// <param name="control"></param>
private void ClearControls(Control control)
{
for (int i=control.Controls.Count -1; i>=0; i--)
{
ClearControls(control.Controls[i]);
}
if(control is TableCell)
{
for(int j = 0 ;j < control.Controls.Count;j++)
{
if(! (control.Controls[j] is Label || control.Controls[j] is LiteralControl))
{
Control c = control.Controls[j];
if(c.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
literal.Text = c.GetType().GetProperty("Text").GetValue(c,null).ToString();
control.Controls.Add(literal);
}
control.Controls.Remove(c);
}
}
}
return;
}
}
/// <summary>
/// 导出的文件类型
/// </summary>
public enum ExportFileType
{
Word = 1,
Excel = 2
}
}

ps:更新了一下代码,另外如果DataGrid中包含类似LinkButton这样的控件,绑定值的时候应该使用

<xmp>&lt;asp:LinkButton Text='"&lt;%#DataBinder.Eval(Container,&amp;#8220;columnName&amp;#8220;)%&gt;"'&gt;&lt;/asp:LinkButton&gt;</xmp>

,而不要使用

<xmp>&lt;asp:LinkButton&gt;&lt;%#DataBinder.Eval(Container,&amp;#8220;columnName&amp;#8220;)%&gt;&lt;/asp:LinkButton&gt;</xmp>

这样的形式,因为这样Text将不会被倒入Excel中

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics