2015-12-23 54 views
0

我叫蘭,請幫我。 //對不起語言//用直放站導出表格到excel

我需要導出一個帶有中繼器的表格html到excel。

我的表結構

<table ID="TblExcel"> 
     <tr> 
      <th style="">Id</th> 
      <th style="">name</th> 
      <th style="">date1</th> 
      <th style="">Expire</th> 
      <th style="">$</th> 
     </tr> <asp:Repeater ID="datarepeat" runat="server"> 
      <ItemTemplate> 
        <tr> 
        <td ><%# DataBinder.Eval(Container.DataItem, "Id")%>/td> 
        <td><%# DataBinder.Eval(Container.DataItem, "Name") %></td> 
        <td ><%# DataBinder.Eval(Container.DataItem, "date1", "{0:d/M/yyyy}") %></td> 
        <td ><%# DataBinder.Eval(Container.DataItem, "Date2", "{0:d/M/yyyy}") %></td> 
>      <td ><%# DataBinder.Eval(Container.DataItem, "Cost") %></td> /tr> 
      </ItemTemplate> 
     </asp:Repeater> 
    </table> 

    <asp:Button ID="Button1" runat="server" OnClick="ExportToExcel" 
Text="2Excel" /> 

代碼:

protected void ExportToExcel(object sender, EventArgs e) 
     { 
      Response.Clear(); 
      Response.Buffer = true; 
      Response.AddHeader("content-disposition", "attachment;filename=Custodias.xls"); 
      Response.ContentEncoding = System.Text.Encoding.UTF8; 
      Response.Charset = "UTF-8"; 
      Response.ContentType = "application/vnd.ms-excel.12"; 
      StringWriter sw = new StringWriter(); 
      HtmlTextWriter hw = new HtmlTextWriter(sw); 
      dlExcel.RenderControl(hw); 
      Response.Output.Write(sw.ToString()); 
      Response.Flush(); 
      Response.End(); 

     } 

而結果在Excel文件是這樣的: NO正確的格式 Image with output excel file

Coments,code或wave是很好的預期。 LAN PD:對不起我的BR lenguage

回答

0

你需要附上打開的表HTML標籤<TABLE>並關閉表標籤</TABLE>之間的所有字符串輸出。

例如,此代碼應工作...

  string output = "<table>" + sw.ToString() + "</table>"; 
      Response.Output.Write(output); 

整個代碼...

protected void ExportToExcel(object sender, EventArgs e) 
     { 
      Response.Clear(); 
      Response.Buffer = true; 
      Response.AddHeader("content-disposition", "attachment;filename=Custodias.xls"); 
      Response.ContentEncoding = System.Text.Encoding.UTF8; 
      Response.Charset = "UTF-8"; 
      Response.ContentType = "application/vnd.ms-excel.12"; 
      StringWriter sw = new StringWriter(); 
      HtmlTextWriter hw = new HtmlTextWriter(sw); 
      dlExcel.RenderControl(hw); 
      string output = "<table>" + sw.ToString() + "</table>"; 
      Response.Output.Write(output); 
      Response.Flush(); 
      Response.End(); 

     }