日期:2014-05-18  浏览次数:20431 次

|M| 第二贴:如何将一个我用Repeater输出的Table转为Execl导出 谢谢 急
http://community.csdn.net/Expert/topic/5558/5558008.xml?temp=.6493799
用幕白兄的:
public   static   void   ExportExcel(ref   System.Web.UI.WebControls.Repeater   rp,   string   strFileName)
{
//DataTable   dt   =   (DataTable)this.Session[ "GridToExcel "];
//if   (dt==null)   return;
strFileName=   System.Web.HttpUtility.UrlEncode(strFileName,System.Text.Encoding.UTF8);

 
//dtgList.DataSource   =   DataClass.ExecuteDataTable(dtgList.strSQL).DefaultView;
//dtgList.EnableViewState   =false;
System.Web.HttpContext.Current.Response.Clear();  
System.Web.HttpContext.Current.Response.Buffer   =   true;  
System.Web.HttpContext.Current.Response.Charset   =   "gb2312 ";
System.Web.HttpContext.Current.Response.AppendHeader( "Content-Disposition ",   "online;   filename= "   +   strFileName   +   ".xls ");
System.Web.HttpContext.Current.Response.ContentEncoding   =   System.Text.Encoding.GetEncoding( "gb2312 ");
System.Web.HttpContext.Current.Response.ContentType   =   "application/ms-excel ";
//System.Web.HttpContext.Current.EnableViewState   =   false;
System.Globalization.CultureInfo   myCItrad   =   new   System.Globalization.CultureInfo( "zh-CN ",true);
System.IO.StringWriter   oStringWriter   =   new   System.IO.StringWriter(myCItrad);  
System.Web.UI.HtmlTextWriter   oHtmlTextWriter   =   new   System.Web.UI.HtmlTextWriter(oStringWriter);
//oHtmlTextWriter.Write( " <table   width= '100% '   border= '1 '> ");
rp.RenderControl(oHtmlTextWriter);  
//oHtmlTextWriter.Write( " </table> ");
rp   =   null;
System.Web.HttpContext.Current.Response.Write(oStringWriter.ToString().Replace( " <td ", " <td   STYLE= 'MSO-NUMBER-FORMAT:\\@ ' "));
System.Web.HttpContext.Current.Response.Buffer   =   false;  
System.Web.HttpContext.Current.Response.End();
}
---------------------------
可以生成
但是当我的repeater中包括了控件的时候就会出错:
类型“CheckBox”的控件“rp_ctl01_CheckBox3”必须放在具有   runat=server   的窗体标记内。

谢谢

------解决方案--------------------
http://blog.csdn.net/ChengKing/category/292667.aspx
------解决方案--------------------
直接将table(服务器控件)render成html然后作为字符串流下载:

/// <summary> 控件存现为Html字符串 </summary>
public static string RenderHtml(Control c){
StringBuilder b = new StringBuilder();
StringWriter w = new StringWriter(b);
HtmlTextWriter htw = new HtmlTextWriter(w);
c.RenderControl(htw);
c.Dispose();
return b.ToString();
}

下载:
public static void ExportString(string s,string fileName){

HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ContentEncoding = System.Text.Encoding.GetEncoding( "gb2312 ");
response.AppendHeader( "Content-Disposition ", "attachment; filename= "+fileName);

response.ContentType = GetMime(fileName);
StreamWriter writer = new StreamWriter(response.OutputStream,response.ContentEncoding);
try {
writer.Write(s);
writer.Flush();
}
finally {
writer.Close();
response.End();
}
}