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

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
 }
}
调用方法

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

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

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

,而不要使用

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值