jasel jasel - 3 months ago 36
C# Question

Export DataGridView to HTML Page

I have tried to find an answer to this question and I have not had any success. My issue is this. I have a comboBox that lists different formats to export a report to. One of those options is HTML. Basically what I want to do is take the dataGridView in a windows form and export as is to an HTML page. I would like to just export to an HTML table. I don't even know how to start on this so I don't have any sample code to provide. I am using c sharp 2008 windows app. Any advise would be greatly appreciated.

Answer
private StringBuilder DataGridtoHTML(DataGridView dg)
{
  StringBuilder strB = new StringBuilder();
  //create html & table
  strB.AppendLine("<html><body><center><" + 
                "table border='1' cellpadding='0' cellspacing='0'>");
  strB.AppendLine("<tr>");
  //cteate table header
  for (int i = 0; i < dg.Columns.Count; i++)
  {
     strB.AppendLine("<td align='center' valign='middle'>" + 
                    dg.Columns[i].HeaderText + "</td>");
   }
  //create table body
  strB.AppendLine("<tr>");
  for (int i = 0; i < dg.Rows.Count; i++)
  {
    strB.AppendLine("<tr>");
    foreach (DataGridViewCell dgvc in dg.Rows[i].Cells)
    {
        strB.AppendLine("<td align='center' valign='middle'>" + 
                        dgvc.Value.ToString() + "</td>");
    }
    strB.AppendLine("</tr>");

}
//table footer & end of html file
strB.AppendLine("</table></center></body></html>");
return strB;} 

The code above is from the link below but I am just giving you what you need which is DataGridView to HTML conversion.

DataGridView to Email