Creating HTML from a DataTable using C#

后端 未结 9 1495
盖世英雄少女心
盖世英雄少女心 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

    Loop over your DataTable, and build up the html string. IE:

    DataTable dt = new DataTable();
    
    dt.Columns.Add("col1");
    dt.Columns.Add("col2");
    dt.Columns.Add("col3");
    dt.Rows.Add(new object[] { "a", "b", "c" });
    dt.Rows.Add(new object[] { "d", "e", "f" });
    
    string tab = "\t";
    
    StringBuilder sb = new StringBuilder();
    
    sb.AppendLine("");
    sb.AppendLine(tab + "");
    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)
    {
        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}
    "); sb.AppendLine(tab + ""); sb.AppendLine("");

提交回复
热议问题