Creating HTML from a DataTable using C#

后端 未结 9 1496
盖世英雄少女心
盖世英雄少女心 2020-12-30 11:37

I need to be able to pass HTML data into Outlook like this:

MailMessage message = new MailMessage();
message.Body = myBody;

Initially, I th

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 12:32

    This is my version of it, with added the possibility to "highlight" some rows based on a generic rule (rowHighlightRule parameter).

      public static string ToHTML(this DataTable dt, Func rowHiglithRule)
        {
    
            if (dt == null) throw new ArgumentNullException("dt");
    
            string tab = "\t";
    
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(tab + tab + "");
    
            // headers.
            sb.Append(tab + tab + tab + "");
    
            foreach (DataColumn dc in dt.Columns)
            {
                sb.AppendFormat("", dc.ColumnName);
            }
    
            sb.AppendLine("");
    
            // data rows
            foreach (DataRow dr in dt.Rows)
            {
                if (rowHiglithRule != null)
                {
    
                    if (rowHiglithRule(dr))
                    {
                        sb.Append(tab + tab + tab + "");
                    }
                    else
                    {
                        sb.Append(tab + tab + tab + "");
                    }
                }
                else
                {
                    //Non ho alcuna regola, quindi caso normale.
                    sb.Append(tab + tab + tab + "");
                }
    
                foreach (DataColumn dc in dt.Columns)
                {
                    string cellValue = dr[dc] != null ? dr[dc].ToString() : "";
                    sb.AppendFormat("", cellValue);
                }
    
                sb.AppendLine("");
            }
    
            sb.AppendLine(tab + tab + "
    {0}
    {0}
    "); return sb.ToString(); }

提交回复
热议问题