Export to Excel from a Repeater?

前端 未结 3 1907
执念已碎
执念已碎 2021-01-05 12:37

Right now I am using this to export a repeater (with multiple nested repeaters) to excel:

protected void ExportToExcel(object sender, EventArgs e) 
{     
Re         


        
相关标签:
3条回答
  • 2021-01-05 12:52

    You need to enclose all of that in table tags. Excel can understand HTML table structures.

    Try:

    Response.Write("<table>");
    Response.Write(stringWrite.ToString()); 
    Response.Write("</table>");
    
    0 讨论(0)
  • 2021-01-05 13:05

    you should make the output file a proper html file, with the html and body tags. That should work better.

    0 讨论(0)
  • 2021-01-05 13:16

    not to answer your question directly, but given you my opinion

    for that kinda of data, is in my opinion that you should use a GridView control, taking your example you will need to write something like:

    <asp:Repeater ID="rpt" runat="server" DataSourceID="ods">
        <HeaderTemplate>
            <table>
            <tr>
                <td>Header</td>
                <td>Type</td>
                <td>Name</td>
                <td>Date</td>
                <td>Amount</td>
            </tr>
        </HeaderTemplate>
        <ItemTemplate>
            <tr>
                <td>
                    <%#Eval("Header")%>
                </td>
                <td>
                    <%#Eval("Type")%>
                </td>
                <td>
                    <%#Eval("Name")%>
                </td>
                <td>
                    <%#Eval("Date", "{0:d}")%>
                </td>
                <td>
                    <%#Eval("Value", "{0:c}")%>
                </td>
            </tr>
        </ItemTemplate>
        <FooterTemplate>
            </table>
        </FooterTemplate>
    </asp:Repeater>
    

    using a GridView all ou nee dto write in the HTML part is only:

    <asp:GridView ID="gv" runat="server" DataSourceID="ods" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="Header" HeaderText="Header" />
            <asp:BoundField DataField="Type" HeaderText="Type" />
            <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:BoundField DataField="Date" DataFormatString="{0:d}" HeaderText="Date" />
            <asp:BoundField DataField="Value" DataFormatString="{0:c}" HeaderText="Value" />
        </Columns>
    </asp:GridView>
    

    something simpler and easier to read

    you will have much more control using a GridView object rather than a Repeater, and, you will never have that kinda of problems, because rendering the gridView will always came with the table tags.

    Hope it helps

    And BTW, I tested your case and i did not got any problems even if I was not writting the tags like Spencer mention.

    to see my code: File with HTML and Method - File with myObject

    0 讨论(0)
提交回复
热议问题