Answered by:
How to transfer html table data into excel sheet?

Question
-
User2141680184 posted
hi
i want to transfer html table data into excel sheet
plz help
Monday, February 4, 2008 4:12 AM
Answers
-
User2022958948 posted
Hi,
You can retrieve the Table from HTML in Code Behind, and export the innerText of HTML Table into the DataSet. Thus you should write a new excel file with DataSet.
There is a completed sample as below.
HTML:
Please set table id property which will be called in Code Behind. And please make sure the table is runat=server.
<table id="table1" runat="server"> <tr> <td>tes1</td> <td>tes2</td> </tr> <tr> <td>tete1</td> <td>tete2</td> </tr> </table>
private DataSet GetTableCellsToDataSet()
{
HtmlTable tb = table1; //table1 is the id of HTML Table
int rowscount = table1.Rows.Count;
int columncount = 2;
DataTable dt=new DataTable();
dt.Columns.Add("a1", Type.GetType("System.String"));
dt.Columns.Add("a2", Type.GetType("System.String"));
for (int i = 0; i < rowscount; i++)
{
HtmlTableCellCollection tcs = tb.Rows[i].Cells;
DataRow dr = dt.NewRow();
dr["a1"] = tcs[0].InnerText;
dr["a2"] = tcs[1].InnerText;
dt.Rows.Add(dr);
}
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
private void convertToExcel(DataSet dsBook) { try { int rows = dsBook.Tables[0].Rows.Count + 1; int cols = dsBook.Tables[0].Columns.Count; string ExcelFileName = Path.Combine(Request.PhysicalApplicationPath, "abcd.xls"); if (File.Exists(ExcelFileName)) { File.Delete(ExcelFileName); } StreamWriter writer = new StreamWriter(ExcelFileName, false); writer.WriteLine("<?xml version=\"1.0\"?>"); writer.WriteLine("<?mso-application progid=\"Excel.Sheet\"?>"); writer.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\""); writer.WriteLine(" xmlns:o=\"urn:schemas-microsoft-com:office:office\""); writer.WriteLine(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\""); writer.WriteLine(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\""); writer.WriteLine(" xmlns:html=\"http://www.w3.org/TR/REC-html40/\">"); writer.WriteLine(" <DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">"); writer.WriteLine(" <Author>Automated Report Generator Example</Author>"); writer.WriteLine(string.Format(" <Created>{0}T{1}Z</Created>", DateTime.Now.ToString("yyyy-mm-dd"), DateTime.Now.ToString("HH:MM:SS"))); writer.WriteLine(" <Company>51aspx.com</Company>"); writer.WriteLine(" <Version>11.6408</Version>"); writer.WriteLine(" </DocumentProperties>"); writer.WriteLine(" <ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">"); writer.WriteLine(" <WindowHeight>8955</WindowHeight>"); writer.WriteLine(" <WindowWidth>11355</WindowWidth>"); writer.WriteLine(" <WindowTopX>480</WindowTopX>"); writer.WriteLine(" <WindowTopY>15</WindowTopY>"); writer.WriteLine(" <ProtectStructure>False</ProtectStructure>"); writer.WriteLine(" <ProtectWindows>False</ProtectWindows>"); writer.WriteLine(" </ExcelWorkbook>"); writer.WriteLine(" <Styles>"); writer.WriteLine(" <Style ss:ID=\"Default\" ss:Name=\"Normal\">"); writer.WriteLine(" <Alignment ss:Vertical=\"Bottom\"/>"); writer.WriteLine(" <Borders/>"); writer.WriteLine(" <Font/>"); writer.WriteLine(" <Interior/>"); writer.WriteLine(" <Protection/>"); writer.WriteLine(" </Style>"); writer.WriteLine(" <Style ss:ID=\"s21\">"); writer.WriteLine(" <Alignment ss:Vertical=\"Bottom\" ss:WrapText=\"1\"/>"); writer.WriteLine(" </Style>"); writer.WriteLine(" </Styles>"); writer.WriteLine(" <Worksheet ss:Name=\"MyReport\">"); writer.WriteLine(string.Format(" <Table ss:ExpandedColumnCount=\"{0}\" ss:ExpandedRowCount=\"{1}\" x:FullColumns=\"1\"", cols.ToString(), rows.ToString())); writer.WriteLine(" x:FullRows=\"1\">"); //generate title writer.WriteLine("<Row>"); foreach (DataColumn eachCloumn in dsBook.Tables[0].Columns) { writer.Write("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">"); writer.Write(eachCloumn.ColumnName.ToString()); writer.WriteLine("</Data></Cell>"); } writer.WriteLine("</Row>"); //generate data foreach (DataRow eachRow in dsBook.Tables[0].Rows) { writer.WriteLine("<Row>"); for (int currentRow = 0; currentRow != cols; currentRow++) { writer.Write("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">"); writer.Write(eachRow[currentRow].ToString()); writer.WriteLine("</Data></Cell>"); } writer.WriteLine("</Row>"); } writer.WriteLine(" </Table>"); writer.WriteLine(" <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">"); writer.WriteLine(" <Selected/>"); writer.WriteLine(" <Panes>"); writer.WriteLine(" <Pane>"); writer.WriteLine(" <Number>3</Number>"); writer.WriteLine(" <ActiveRow>1</ActiveRow>"); writer.WriteLine(" </Pane>"); writer.WriteLine(" </Panes>"); writer.WriteLine(" <ProtectObjects>False</ProtectObjects>"); writer.WriteLine(" <ProtectScenarios>False</ProtectScenarios>"); writer.WriteLine(" </WorksheetOptions>"); writer.WriteLine(" </Worksheet>"); writer.WriteLine(" <Worksheet ss:Name=\"Sheet2\">"); writer.WriteLine(" <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">"); writer.WriteLine(" <ProtectObjects>False</ProtectObjects>"); writer.WriteLine(" <ProtectScenarios>False</ProtectScenarios>"); writer.WriteLine(" </WorksheetOptions>"); writer.WriteLine(" </Worksheet>"); writer.WriteLine(" <Worksheet ss:Name=\"Sheet3\">"); writer.WriteLine(" <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">"); writer.WriteLine(" <ProtectObjects>False</ProtectObjects>"); writer.WriteLine(" <ProtectScenarios>False</ProtectScenarios>"); writer.WriteLine(" </WorksheetOptions>"); writer.WriteLine(" </Worksheet>"); writer.WriteLine("</Workbook>"); writer.Close(); Response.Write("<script language=\"javascript\">" + "alert('" + "convert completed!')" + "</script>"); } catch (Exception ex) { Response.Write("<script language=\"javascript\">" + "alert('" + "error! " + ex.Message + "')" + "</script>"); } }
After that, you can call it by convertToExcel(GetTableCellsToDataSet());
GetTableCellsToDataSet() will retrieve the HTML Table innerText into a new dataset.
convertToExcel will export the dataset to a excel file.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Tuesday, February 5, 2008 9:56 PM
All replies
-
User437878640 posted
Hi,
u can try the following code,
DataSet ds=objAdmin.getErrorsInDetail();
Response.AppendHeader("Content-Disposition", "attachment; filename=Error.xls") ;
Response.ContentType="application/ms-excel";Response.Write("<table>");
Response.Write("<tr>");
for(int i=0;i<ds.Tables[0].Columns.Count;i++)
{
Response.Write("<td>"+ ds.Tables[0].Columns[i].ColumnName +"</td>");
}
Response.Write("</tr>");
for(int i=0;i<ds.Tables[0].Rows.Count;i++)
{
Response.Write("<tr>");
DataRow row=ds.Tables[0].Rows[i];
for(int j=0;j<ds.Tables[0].Columns.Count;j++)
{
Response.Write("<td>"+ row[j]+"</td>");
}
Response.Write("</tr>");
}
Response.Write("</table>");
Response.End();Monday, February 4, 2008 4:28 AM -
Monday, February 4, 2008 4:32 AM
-
User2141680184 posted
thanx 4 ur reply
i want to export perticular table into excel sheet not whole web page
Monday, February 4, 2008 4:55 AM -
Monday, February 4, 2008 5:05 AM
-
User-1875880351 posted
Here is a simple way to export an HTML table to Excel with a single line of code. For the technique to work, you must have Excel installed on the your machine. Copy the following code and paste it in notepad. Save it as an ASP page, and then open it in the browser to see the action live.
<% The main feature of this technique is that %><% you have to change Content type to ms-excel.%><% The main feature of this technique is that %>
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p><% you have to change Content type to ms-excel.%>Response.ContentType = "application/vnd.ms-excel"
<TABLE><o:p></o:p><TR><TD>2</TD></TR><o:p></o:p><TR><TD>3</TD></TR><o:p></o:p><TR><TD>=SUM(A1:A2)</TD></TR><o:p></o:p></TABLE><o:p></o:p>Don't include normal HTML, TITLE, HEAD, and BODY tags. They will create a problem.Monday, February 4, 2008 5:17 AM -
User2141680184 posted
suppose if there are more than one table in page i want perticular table to be exported in excel not all tables
thnax
Monday, February 4, 2008 5:27 AM -
User2022958948 posted
Hi,
You can retrieve the Table from HTML in Code Behind, and export the innerText of HTML Table into the DataSet. Thus you should write a new excel file with DataSet.
There is a completed sample as below.
HTML:
Please set table id property which will be called in Code Behind. And please make sure the table is runat=server.
<table id="table1" runat="server"> <tr> <td>tes1</td> <td>tes2</td> </tr> <tr> <td>tete1</td> <td>tete2</td> </tr> </table>
private DataSet GetTableCellsToDataSet()
{
HtmlTable tb = table1; //table1 is the id of HTML Table
int rowscount = table1.Rows.Count;
int columncount = 2;
DataTable dt=new DataTable();
dt.Columns.Add("a1", Type.GetType("System.String"));
dt.Columns.Add("a2", Type.GetType("System.String"));
for (int i = 0; i < rowscount; i++)
{
HtmlTableCellCollection tcs = tb.Rows[i].Cells;
DataRow dr = dt.NewRow();
dr["a1"] = tcs[0].InnerText;
dr["a2"] = tcs[1].InnerText;
dt.Rows.Add(dr);
}
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
private void convertToExcel(DataSet dsBook) { try { int rows = dsBook.Tables[0].Rows.Count + 1; int cols = dsBook.Tables[0].Columns.Count; string ExcelFileName = Path.Combine(Request.PhysicalApplicationPath, "abcd.xls"); if (File.Exists(ExcelFileName)) { File.Delete(ExcelFileName); } StreamWriter writer = new StreamWriter(ExcelFileName, false); writer.WriteLine("<?xml version=\"1.0\"?>"); writer.WriteLine("<?mso-application progid=\"Excel.Sheet\"?>"); writer.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\""); writer.WriteLine(" xmlns:o=\"urn:schemas-microsoft-com:office:office\""); writer.WriteLine(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\""); writer.WriteLine(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\""); writer.WriteLine(" xmlns:html=\"http://www.w3.org/TR/REC-html40/\">"); writer.WriteLine(" <DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">"); writer.WriteLine(" <Author>Automated Report Generator Example</Author>"); writer.WriteLine(string.Format(" <Created>{0}T{1}Z</Created>", DateTime.Now.ToString("yyyy-mm-dd"), DateTime.Now.ToString("HH:MM:SS"))); writer.WriteLine(" <Company>51aspx.com</Company>"); writer.WriteLine(" <Version>11.6408</Version>"); writer.WriteLine(" </DocumentProperties>"); writer.WriteLine(" <ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">"); writer.WriteLine(" <WindowHeight>8955</WindowHeight>"); writer.WriteLine(" <WindowWidth>11355</WindowWidth>"); writer.WriteLine(" <WindowTopX>480</WindowTopX>"); writer.WriteLine(" <WindowTopY>15</WindowTopY>"); writer.WriteLine(" <ProtectStructure>False</ProtectStructure>"); writer.WriteLine(" <ProtectWindows>False</ProtectWindows>"); writer.WriteLine(" </ExcelWorkbook>"); writer.WriteLine(" <Styles>"); writer.WriteLine(" <Style ss:ID=\"Default\" ss:Name=\"Normal\">"); writer.WriteLine(" <Alignment ss:Vertical=\"Bottom\"/>"); writer.WriteLine(" <Borders/>"); writer.WriteLine(" <Font/>"); writer.WriteLine(" <Interior/>"); writer.WriteLine(" <Protection/>"); writer.WriteLine(" </Style>"); writer.WriteLine(" <Style ss:ID=\"s21\">"); writer.WriteLine(" <Alignment ss:Vertical=\"Bottom\" ss:WrapText=\"1\"/>"); writer.WriteLine(" </Style>"); writer.WriteLine(" </Styles>"); writer.WriteLine(" <Worksheet ss:Name=\"MyReport\">"); writer.WriteLine(string.Format(" <Table ss:ExpandedColumnCount=\"{0}\" ss:ExpandedRowCount=\"{1}\" x:FullColumns=\"1\"", cols.ToString(), rows.ToString())); writer.WriteLine(" x:FullRows=\"1\">"); //generate title writer.WriteLine("<Row>"); foreach (DataColumn eachCloumn in dsBook.Tables[0].Columns) { writer.Write("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">"); writer.Write(eachCloumn.ColumnName.ToString()); writer.WriteLine("</Data></Cell>"); } writer.WriteLine("</Row>"); //generate data foreach (DataRow eachRow in dsBook.Tables[0].Rows) { writer.WriteLine("<Row>"); for (int currentRow = 0; currentRow != cols; currentRow++) { writer.Write("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">"); writer.Write(eachRow[currentRow].ToString()); writer.WriteLine("</Data></Cell>"); } writer.WriteLine("</Row>"); } writer.WriteLine(" </Table>"); writer.WriteLine(" <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">"); writer.WriteLine(" <Selected/>"); writer.WriteLine(" <Panes>"); writer.WriteLine(" <Pane>"); writer.WriteLine(" <Number>3</Number>"); writer.WriteLine(" <ActiveRow>1</ActiveRow>"); writer.WriteLine(" </Pane>"); writer.WriteLine(" </Panes>"); writer.WriteLine(" <ProtectObjects>False</ProtectObjects>"); writer.WriteLine(" <ProtectScenarios>False</ProtectScenarios>"); writer.WriteLine(" </WorksheetOptions>"); writer.WriteLine(" </Worksheet>"); writer.WriteLine(" <Worksheet ss:Name=\"Sheet2\">"); writer.WriteLine(" <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">"); writer.WriteLine(" <ProtectObjects>False</ProtectObjects>"); writer.WriteLine(" <ProtectScenarios>False</ProtectScenarios>"); writer.WriteLine(" </WorksheetOptions>"); writer.WriteLine(" </Worksheet>"); writer.WriteLine(" <Worksheet ss:Name=\"Sheet3\">"); writer.WriteLine(" <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">"); writer.WriteLine(" <ProtectObjects>False</ProtectObjects>"); writer.WriteLine(" <ProtectScenarios>False</ProtectScenarios>"); writer.WriteLine(" </WorksheetOptions>"); writer.WriteLine(" </Worksheet>"); writer.WriteLine("</Workbook>"); writer.Close(); Response.Write("<script language=\"javascript\">" + "alert('" + "convert completed!')" + "</script>"); } catch (Exception ex) { Response.Write("<script language=\"javascript\">" + "alert('" + "error! " + ex.Message + "')" + "</script>"); } }
After that, you can call it by convertToExcel(GetTableCellsToDataSet());
GetTableCellsToDataSet() will retrieve the HTML Table innerText into a new dataset.
convertToExcel will export the dataset to a excel file.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Tuesday, February 5, 2008 9:56 PM -
User-565695546 posted
If HTML table is generated from ASP.NET GridView control or some other control bounded to DataTable or DataSet then you could try GemBox.Spreadsheet .NET excel library becuase export from DataTable and DataSet are directly supported.
Here is an example how to export DataTable to Excel with GemBox.Spreadsheet library.
Monday, November 9, 2009 5:35 AM -
User1789523204 posted
Response.Buffer = True
Response.AddHeader "content-disposition", "attachment; filename=report name"
Response.ContentType = "application/vnd.ms-excel"place this code into your page
Tuesday, April 27, 2010 5:32 AM -
User9119091 posted
i found the above code very useful. But my excel output contains merged cells, so how i have the mergerd cell headers in the excel output.
please help me..
Friday, June 18, 2010 8:48 AM -
User2086784605 posted
Hi PriyanViji,
It works very well, but It alerts "The file you are trying to open, 'Error.xls', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?"
The file is not working properly. Could you please let me know what is the problem?
Thanks in advance
Savada Sin
savadasin@gmail.com
Tuesday, September 14, 2010 11:57 PM -
User2011061600 posted
You need to copy and paste the table into Word first, then copy and paste from Word to Excel. Going from html to Excel does not work.
1. Highlight the table
2. Copy into MS Word
3. Highlight and copy the table in MS Word (in the newer versions you can simply click on the little box/+ sign in the upper left-hand corner)
4. Paste into Excel
Another option for copying the table into Word is to open the html file in Internet Explorer and click on File > Edit with Microsoft Word. It will then open the entire page in Word. Then copy the table and paste it into Excel
Thursday, June 16, 2011 1:05 PM -
User-1062158585 posted
Hi,
- Add a regular html input button and a .NET HiddenField to the page
- Add an onclick event to that button called "Export"
- Create a javascript function, Export, that stores the return value of table2CSV() into the hidden field, and posts back.
- The server receives the hiddenfield post data (the csv as a string)
- The server outputs the string to the browser as a csv fill
- // javascript function Export()
{ $('#yourHiddenFieldId').val() = $('#yourTable').table2CSV({delivery:'value'});
__doPostBack('#yourExportBtnId', ''); }
// c# if(Page.IsPostBack)
{
if(!String.IsNullOrEmpty(Request.Form[yourHiddenField.UniqueId]))
{
Response.Clear();
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", "attachment; filename=TheReport.csv");
Response.Flush();
Response.Write(Request.Form[yourHiddenField.UniqueID]);
Response.End(); } }
Friday, August 5, 2011 2:05 PM