Reputation: 293
How to export multiple tables to multiple excel sheet using c#? Below code is working but only for 1 html table.
Response.ContentType = "application/x-msexcel";
Response.AddHeader("Content-Disposition", "attachment; filename=ExcelFile.xls");
Response.ContentEncoding = Encoding.UTF8;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
tbl.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
Below are tables in *.aspx page. And i want to both tables in one excel with multiple sheet.
for Example : Table 1 is in worksheet 1 table 2 is in worksheet 2
<table id="tbl" border="1" runat="server" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Available</td>
<td>Count</td>
</tr>
<tr>
<td>Bred</td>
<td>1
</td>
<td>2
</td>
<td>3
</td>
</tr>
<tr>
<td>Butter</td>
<td>4
</td>
<td>5
</td>
<td>6
</td>
</tr>
</table>
<table id="tbl2" border="1" runat="server" >
<tr>
<td>KD</td>
<td>Dabhi</td>
<td>Qnil</td>
<td>Dabhi</td>
</tr>
<tr>
<td>Bred</td>
<td>1
</td>
<td>2
</td>
<td>3
</td>
</tr>
<tr>
<td>Butter</td>
<td>4
</td>
<td>5
</td>
<td>6
</td>
</tr>
</table>
<asp:Button runat="server" ID="ExportToExcelButton" OnClick="ExportToExcelButton_Click"
Text="Export To Excel" />
Upvotes: 0
Views: 4337
Reputation: 5801
Working solution for GridViews is here:
You may want to look also here for some advise:
Add table to second sheet of Excel using C#
You may want to use EPPLUS library (free) instead of interop because it has a lot of functionality:
Upvotes: 0
Reputation: 17182
In the example you mentioned, you are NOT
creating an Excel (or Excel WorkSheets), instead you are trying to open HTML content in Excel format. That is the reason, even if you have TWO
Tables, they will show up in single sheet.
Use Microsoft's OpenXml SDK, through which you can create any number of Sheets and inject data into sheets. Even OpenXml SDK got some minor issues when it comes to Date Type (especially while reading data from Excel sheets). In such a case you can go to any third party Excel automation providers like SpreadSheetGear.
Upvotes: 2