Click here to Skip to main content
16,019,976 members
Articles / Programming Languages / C#
Tip/Trick

Convert HTMLTable to Comma Separated Values

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
5 Jan 2011CPOL 31.1K   3   1
A simple class that converts HTMLTable to CSV
This is a simple class that takes an HTMLTable in the constructor and returns an array of strings in CSV format.

C#
namespace WebLib
{
    using System.Collections.Generic;
    using System.Text;
    using System.Web.UI.HtmlControls;

    public class HTMLTableHelper
    {
        #region Fields

        private readonly HtmlTable htmlTable;

        #endregion
        
        #region Constructors

        public HTMLTableHelper(HtmlTable htmlTable)
        {
            this.htmlTable = htmlTable;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Converts HTML Table to Comma Seperated Values structure.
        /// </summary>
        /// <returns></returns>
        public string[] ConvertToCSV()
        {
            //Will hold all rows of table as CSV
            List<string> rows = new List<string>();

            //Loop through each row in the HTML table
            foreach (HtmlTableRow row in htmlTable.Rows)
            {
                StringBuilder rowCVS = new StringBuilder();
                //Loop through each cell in the row
                foreach (HtmlTableCell cell in row.Cells)
                {
                    //Appends cell Text to rowCVS
                    rowCVS.Append(cell.TagName.Trim());
                    //Adds comma after text
                    rowCVS.Append(","); 
                }
                //Removes last Comma from row
                rowCVS.Remove(rowCVS.Length - 1, 1);
                //Add cvs row to list of rows
                rows.Add(rowCVS.ToString());
            }

            return rows.ToArray();
        }

        #endregion
    }
}


In the hope that it might prove useful,
Jethro Badenhorst

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
South Africa South Africa
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralUsage of this class Pin
Dannoman123416-Feb-11 6:17
Dannoman123416-Feb-11 6:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.