locked
convert a DataTable to HTML RRS feed

  • Question

  • User-1614457691 posted

     

    FYI, below is one way to convert a DataTable to HTML.

    Here is the code...

     

    /// <summary>
    /// This is a simple way to convert a DataTable to an HTML file.
    /// </summary>
    /// <param name="targetTable">This the table to convert.</param>
    /// <returns>This is the HTML output, which can saved as a file.</returns>
    public static string ConvertToHtmlFile(DataTable targetTable)
    {
     string myHtmlFile = "";

     if (targetTable == null)
     {
      throw new System.ArgumentNullException("targetTable");
     }
     else
     {
      //Continue.
     }

     //Get a worker object.
     StringBuilder myBuilder = new StringBuilder();

     //Open tags and write the top portion.
     myBuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'>");
     myBuilder.Append("<head>");
     myBuilder.Append("<title>");
     myBuilder.Append("Page-");
     myBuilder.Append(Guid.NewGuid().ToString());
     myBuilder.Append("</title>");
     myBuilder.Append("</head>");
     myBuilder.Append("<body>");
     myBuilder.Append("<table border='1px' cellpadding='5' cellspacing='0' ");
     myBuilder.Append("style='border: solid 1px Silver; font-size: x-small;'>");

     //Add the headings row.

     myBuilder.Append("<tr align='left' valign='top'>");

     foreach (DataColumn myColumn in targetTable.Columns)
     {
      myBuilder.Append("<td align='left' valign='top'>");
      myBuilder.Append(myColumn.ColumnName);
      myBuilder.Append("</td>");
     }

     myBuilder.Append("</tr>");

     //Add the data rows.
     foreach (DataRow myRow in targetTable.Rows)
     {
      myBuilder.Append("<tr align='left' valign='top'>");

      foreach (DataColumn myColumn in targetTable.Columns)
      {
       myBuilder.Append("<td align='left' valign='top'>");
       myBuilder.Append(myRow[myColumn.ColumnName].ToString());
       myBuilder.Append("</td>");
      }

      myBuilder.Append("</tr>");
     }

     //Close tags.
     myBuilder.Append("</table>");
     myBuilder.Append("</body>");
     myBuilder.Append("</html>");

     //Get the string for return.
     myHtmlFile = myBuilder.ToString();

     return myHtmlFile;
    }

    HTH.

    Thank you.

    -- Mark Kamoski

    Friday, March 30, 2007 4:14 PM

All replies

  • User1001868398 posted

    Mark,

    Why not bind the dataTable into a GridView or DataGrid so will get the result on the web page that you are looking for

    Saturday, March 31, 2007 11:24 AM
  • User-1614457691 posted

    Mark,

    Why not bind the dataTable into a GridView or DataGrid so will get the result on the web page that you are looking for

    My requirements called for getting an entire, valid, text for an HTML page in a string, and then another process takes that and creates an actual, physical HTML file on disk.

    I started looked at making a GridView in-memory, streaming it to TextWriter or HtmlWriter, getting that text, adding the HTML opening and closing tags, etc-- but, that was more work (or at least the same amount of work), than just looping and doing simple string manipulation, IMHO.

    I am sure binding to a GridView and outputting that could work-- but, I am not convinced that it is actuallly more simple than what I have shown when the target requirement is as stated above.

    That said, I would be happy to see any other code that can do what I need (get a whole HTML page as a string) via other methods.

     Thank you.

    -- Mark Kamoski 

     

    Saturday, March 31, 2007 8:56 PM
  • User1001868398 posted
    Well you can always create a control inherit from compositecontrol and have a gridview as a private member binding it on the constructor and render OnRender using the HtmlWriter, that'll will fullfil your requierement I believe.
    Sunday, April 1, 2007 10:47 AM
  • User887723694 posted

    I need to do the same in a windows service. can i do the same using a datagrid??

    Friday, September 21, 2007 5:15 AM
  • User1347187933 posted

    Well you can always create a control inherit from compositecontrol and have a gridview as a private member binding it on the constructor and render OnRender using the HtmlWriter, that'll will fullfil your requierement I believe.
     

    Good Idea. 

    Friday, September 28, 2007 12:02 AM
  • User-1367805312 posted

    Well you can always create a control inherit from compositecontrol and have a gridview as a private member binding it on the constructor and render OnRender using the HtmlWriter, that'll will fullfil your requierement I believe.
     

    You don't fancy giving us an example of doing this do you?  And if you are in a real good mood, how about in ASP.NET using VB as I don't use C# yet...?? 

    Friday, October 5, 2007 4:13 AM
  • User-1614457691 posted

    ...how about in ASP.NET using VB as I don't use C# yet...?? 

     

    FWIW, here is a VB version of my C# sample above...

     

    ''' This provides a simple way to convert a DataTable to an HTML file.
    ''' </summary>
    ''' <param name="targetTable">This the table to convert.</param>
    ''' <returns>This is the HTML output, which can saved as a file.</returns>
    Public Shared Function ConvertToHtmlFile(ByVal targetTable As DataTable) As String
        Dim myHtmlFile As String = ""
    
        If (targetTable Is Nothing) Then
            Throw New System.ArgumentNullException("targetTable")
        Else
            'Continue.
        End If
    
        'Get a worker object.
        Dim myBuilder As System.Text.StringBuilder = New System.Text.StringBuilder()
    
        'Open tags and write the top portion.
        myBuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'>")
        myBuilder.Append("<head>")
        myBuilder.Append("<title>")
        myBuilder.Append("Page-")
        myBuilder.Append(Guid.NewGuid().ToString())
        myBuilder.Append("</title>")
        myBuilder.Append("</head>")
        myBuilder.Append("<body>")
        myBuilder.Append("<table border='1px' cellpadding='5' cellspacing='0' ")
        myBuilder.Append("style='border: solid 1px Silver; font-size: x-small;'>")
    
        'Add the headings row.
    
        myBuilder.Append("<tr align='left' valign='top'>")
    
        For Each myColumn As DataColumn In targetTable.Columns
            myBuilder.Append("<td align='left' valign='top'>")
            myBuilder.Append(myColumn.ColumnName)
            myBuilder.Append("</td>")
        Next myColumn
    
        myBuilder.Append("</tr>")
    
    
        'Add the data rows.
        For Each myRow As DataRow In targetTable.Rows
            myBuilder.Append("<tr align='left' valign='top'>")
    
            For Each myColumn As DataColumn In targetTable.Columns
                myBuilder.Append("<td align='left' valign='top'>")
                myBuilder.Append(myRow(myColumn.ColumnName).ToString())
                myBuilder.Append("</td>")
            Next myColumn
    
    
            myBuilder.Append("</tr>")
        Next myRow
    
        'Close tags.
        myBuilder.Append("</table>")
        myBuilder.Append("</body>")
        myBuilder.Append("</html>")
    
        'Get the string for return.
        myHtmlFile = myBuilder.ToString()
    
        Return myHtmlFile
    End Function
    
      

     

     

    Tuesday, October 30, 2007 10:10 PM
  • User1879672309 posted

    easiet way of doing this , i think this can be helpfull in  a senario of generating email with dynamic content (from db) as well. 

    Wednesday, October 31, 2007 1:04 AM
  • User-1235130859 posted

    Yes I did,

    I can give the code as a DLL, mail me if you need.

    cheers...

    Monday, June 14, 2010 3:26 AM
  • User1016609979 posted

    Thanks Man. I have done the same work like this.

    DataTable dtPriceDetails = SOME DATA TABLE 
    
    if (dt.Rows.Count > 0)
    {
    string StringDataTable = ConvertToHtmlFile(dtPriceDetails);
    }
    
      public static string ConvertToHtmlFile(DataTable targetTable)
      {
      	string myHtmlFile = "";
    
    if (targetTable == null)
          {
          	throw new System.ArgumentNullException("targetTable");
    }
          else
          {
          	//Continue. 
    }
    
    //Get a worker object.
          StringBuilder myBuilder = new StringBuilder();
    
          //Open tags and write the top portion. 
          //myBuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'>");
          //myBuilder.Append("<head>");
          //myBuilder.Append("<title>");
          //myBuilder.Append("Page-");
          //myBuilder.Append(Guid.NewGuid().ToString());
          //myBuilder.Append("</title>");
          //myBuilder.Append("</head>");
          //myBuilder.Append("<body>");
          myBuilder.Append("<table border='1px' cellpadding='5' cellspacing='0' ");
          myBuilder.Append("style='border: solid 1px Silver; font-size: x-small;'>");
    
    //Add the headings row.
          myBuilder.Append("<tr align='left' valign='top'>");
    foreach (DataColumn myColumn in targetTable.Columns)
          {
          	myBuilder.Append("<td align='left' valign='top'>");
          myBuilder.Append(myColumn.ColumnName);
          	myBuilder.Append("</td>");
          }
          myBuilder.Append("</tr>");
    
    //Add the data rows. 
          foreach (DataRow myRow in targetTable.Rows)
          {
          	myBuilder.Append("<tr align='left' valign='top'>");
    
    foreach (DataColumn myColumn in targetTable.Columns)
                {
                	myBuilder.Append("<td align='left' valign='top'>");
                      myBuilder.Append(myRow[myColumn.ColumnName].ToString());
                      myBuilder.Append("</td>");
    }
    
                myBuilder.Append("</tr>");
    }
    
          //Close tags. 
          myBuilder.Append("</table>");
          //myBuilder.Append("</body>"); 
          //myBuilder.Append("</html>");
    
          //Get the string for return. 
          myHtmlFile = myBuilder.ToString();
    
          return myHtmlFile;
    }
    



    http://developersmania.blogspot.com/2010/06/convert-datatable-to-html.html

    Tuesday, June 15, 2010 9:18 AM
  • User-1614457691 posted

    smh --

    This is a nice solution.

    Yes, I have seen this before too.

    Most browsers seem to render a document that is bounded by <table></table>, without an <html> tag or <body> tag.

    However, I have always wondered if that is truly a complete HTML file.

    I guess it is, more-or-less, given that it IS valid XHTML-- so, that is a good idea that you have there.

    Thank you.

    -- Mark Kamoski

    Tuesday, June 15, 2010 11:10 AM
  • User-2079636174 posted

    wow such an old thread. but with LINQ now we can show off to other language programmers


    Public Function ConvertToHTMLString(ByVal ADatatable As Data.DataTable) As String
            
            Dim s As New Text.StringBuilder
            
            s.Append("<html><body><table><thead><tr>")
            
            Dim cols = (From a As Data.DataColumn In ADatatable.Columns).ToList
            cols.ForEach(Sub(a) s.AppendFormat("<th>{0}</th>", a.ColumnName))
            
            s.Append("</tr></thead><tbody>")
            
            Dim rows = (From a As Data.DataRow In ADatatable.Rows).ToList
    <strike>        rows.ForEach(Sub(a) cols.ForEach(Sub(b) s.Append("<tr>").AppendFormat("<td>{0}</td>", a(b)).Append("</tr>")))</strike>

    rows.ForEach(Sub(a) s.AppendFormat("<tr>").Append(String.Join(String.Empty, cols.Select(Function(b) "<td>" & a(b) & "</td>").ToArray)).Append("</tr>"))

           
            s.Append("</tbody></table></body></html>")
            
            Return s.ToString
            
        End Function


    Tuesday, June 15, 2010 11:26 PM
  • User-1720981379 posted

    for me this example works to export a datatable to excel, and i want to say thank you

    Monday, August 16, 2010 10:37 AM
  • User1837603760 posted

    Hi

    My need was to convert datatable in into HTML so that i can use that into my outlook to send mails...actaully I am devloping a mail application which send mails instantly without the interaction of any user via sheduler.

    That helped me a lot.

    now albertpascual might understand that why the conversion is to be done only to HTML

    thanx a ton Mark

     

     Regards

    Muktesh T

    Wednesday, August 31, 2011 2:59 AM
  • User-1548778540 posted

    This is probably the most complicated way of accomplishing a simple task.

    I think this is best done with these simple lines of code:

    private string CreateTableHTML(DataTable DT)
    {
            GridView gv = new GridView();
            gv.DataSource = DT;
            gv.DataBind();
            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
            gv.RenderControl(htw);
            return htw.InnerWriter.ToString();
    }
    Wednesday, August 31, 2011 9:49 AM
  • User-2097060974 posted

    Everyone always gives

    myBuilder.Append(myRow[myColumn.ColumnName].ToString()); 

    as the answer for how to write the value of a column and puts it in a loop through the columns.

    1. It's the lazy way out (you don't have to know the column name)
    2. You have no control over what you're writing - it will just write everything.

    Because what do you do if you don't want to write everything?  Maybe you just want 1 or 2 specific columns?

    The way you'd do this is to specify that column:

    myBuilder.Append(myRow["myColumnName"].ToString()); 
    

    where "myColumnName" is the actual ColumnName you want the value of and you don't include that loop through the Columns to get this.  You have more control over what you write if you do it this way.

    Thursday, June 21, 2012 1:43 AM