数据表到html表

时间:2013-10-30 13:02:51

标签: c# asp.net datatable

我有疑问,也许这里有人不介意帮助我。我可以说3个数据表,每个数据表都有以下列:

尺寸,数量,数量,持续时间

数据表和值的名称

LivingRoom
================
1
1
1
1
2
2
2
2

BathRoom
================
3
3
3
3
4
4
4
4

BedRoom
=================
5
5
5
5
6
6
6
6

现在我正在尝试构建一个html发票,我可以循环遍历所有数据表并输出以下html输出,非常基本:

<table>
<tr>
    <td>Area</td>
</tr>
<tr>
    <td>Living Room</td>
</tr>

<tr>
    <td>Size</td>
    <td>Quantity</td>
    <td>Amount</td>
    <td>Duration</td>
</tr>
<tr>
    <td>1</td>
    <td>1</td>
    <td>1</td>
    <td>1</td>
</tr>
<tr>
    <td>2</td>
    <td>2</td>
    <td>2</td>
    <td>2</td>
</tr>

<tr>
    <td>Area</td>
</tr>
<tr>
    <td>Bathroom</td>
</tr>

<tr>
    <td>Size</td>
    <td>Quantity</td>
    <td>Amount</td>
    <td>Duration</td>
</tr>
<tr>
    <td>3</td>
    <td>3</td>
    <td>3</td>
    <td>3</td>
</tr>
<tr>
    <td>4</td>
    <td>4</td>
    <td>4</td>
    <td>4</td>
</tr>

<tr>
    <td>Area</td>
</tr>
<tr>
    <td>Bedroom</td>
</tr>

<tr>
    <td>Size</td>
    <td>Quantity</td>
    <td>Amount</td>
    <td>Duration</td>
</tr>
<tr>
    <td>5</td>
    <td>5</td>
    <td>5</td>
    <td>5</td>
</tr>
<tr>
    <td>6</td>
    <td>6</td>
    <td>6</td>
    <td>6</td>
</tr>
</table>

因此,该区域将具有数据表的名称,然后在每个区域下循环该特定数据表并以该格式输出数据。我无法弄清楚循环逻辑或如何做到这一点,我最近几天一直在打破这个问题。也许我只是以错误的方式思考它,但我真的可以在这方面使用一些帮助。

10 个答案:

答案 0 :(得分:102)

使用此功能:

    public static string ConvertDataTableToHTML(DataTable dt)
    {
        string html = "<table>";
        //add header row
        html += "<tr>";
        for(int i=0;i<dt.Columns.Count;i++)
            html+="<td>"+dt.Columns[i].ColumnName+"</td>";
        html += "</tr>";
        //add rows
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            html += "<tr>";
            for (int j = 0; j< dt.Columns.Count; j++)
                html += "<td>" + dt.Rows[i][j].ToString() + "</td>";
            html += "</tr>";
        }
        html += "</table>";
        return html;
    }

答案 1 :(得分:11)

public static string toHTML_Table(DataTable dt)
{
    if (dt.Rows.Count == 0) return ""; // enter code here

    StringBuilder builder = new StringBuilder();
    builder.Append("<html>");
    builder.Append("<head>");
    builder.Append("<title>");
    builder.Append("Page-");
    builder.Append(Guid.NewGuid());
    builder.Append("</title>");
    builder.Append("</head>");
    builder.Append("<body>");
    builder.Append("<table border='1px' cellpadding='5' cellspacing='0' ");
    builder.Append("style='border: solid 1px Silver; font-size: x-small;'>");
    builder.Append("<tr align='left' valign='top'>");
    foreach (DataColumn c in dt.Columns)
    {
        builder.Append("<td align='left' valign='top'><b>");
        builder.Append(c.ColumnName);
        builder.Append("</b></td>");
    }
    builder.Append("</tr>");
    foreach (DataRow r in dt.Rows)
    {
        builder.Append("<tr align='left' valign='top'>");
        foreach (DataColumn c in dt.Columns)
        {
            builder.Append("<td align='left' valign='top'>");
            builder.Append(r[c.ColumnName]);
            builder.Append("</td>");
        }
        builder.Append("</tr>");
    }
    builder.Append("</table>");
    builder.Append("</body>");
    builder.Append("</html>");

    return builder.ToString();
}

答案 2 :(得分:9)

我已经看到一些值得注意的解决方案,正如Omer Eldan所说。但是接下来。 ASP C#

using System.Data;
using System.Web.UI.HtmlControls;

public static Table DataTableToHTMLTable(DataTable dt, bool includeHeaders)
{
    Table tbl = new Table();
    TableRow tr = null;
    TableCell cell = null;

    int rows = dt.Rows.Count;
    int cols = dt.Columns.Count;

    if (includeHeaders)
    {
        TableHeaderRow htr = new TableHeaderRow();
        TableHeaderCell hcell = null;
        for (int i = 0; i < cols; i++)
        {
            hcell = new TableHeaderCell();
            hcell.Text = dt.Columns[i].ColumnName.ToString();
            htr.Cells.Add(hcell);
        }
        tbl.Rows.Add(htr);
    }

    for (int j = 0; j < rows; j++)
    {
        tr = new TableRow();
        for (int k = 0; k < cols; k++)
        {
            cell = new TableCell();
            cell.Text = dt.Rows[j][k].ToString();
            tr.Cells.Add(cell);
        }
        tbl.Rows.Add(tr);
    }
    return tbl;
}

为什么这个解决方案? 因为您可以轻松地将其添加到面板中,即:

panel.Controls.Add(DataTableToHTMLTable(dtExample,true));

第二个问题,为什么你有一个列数据表而不仅仅是数组? 你确定这些DataTable是统一的,因为如果数据是锯齿状的,那么它就没用了。 如果你真的必须加入这些DataTables,那么有很多Linq操作的例子,或者只是使用(请注意相同名称列,因为如果不处理,这将在linq操作和此解决方案中发生冲突):

public DataTable joinUniformTable(DataTable dt1, DataTable dt2)
{
    int dt2ColsCount = dt2.Columns.Count;
    int dt1lRowsCount = dt1.Rows.Count;

    DataColumn column;
    for (int i = 0; i < dt2ColsCount; i++)
    {
        column = new DataColumn();
        string colName = dt2.Columns[i].ColumnName;
        System.Type colType = dt2.Columns[i].DataType;
        column.ColumnName = colName;
        column.DataType = colType;
        dt1.Columns.Add(column);

        for (int j = 0; j < dt1lRowsCount; j++)
        {
            dt1.Rows[j][colName] = dt2.Rows[j][colName];
        }
    }
    return dt1;
}

你的解决方案看起来像:

panel.Controls.Add(DataTableToHTMLTable(joinUniformTable(joinUniformTable(LivDT,BathDT),BedDT),true));

解释其余部分,并享受乐趣。

答案 3 :(得分:4)

第一个答案是正确的,但是如果你有大量的数据(在我的项目中,我有8.000行* 8列)是悲惨的...... 在c#中有一个变大的字符串是为什么这个解决方案是forbiden

使用大字符串我使用了最后加入的字符串数组,以便返回html表的字符串。此外,我使用了一个linq表达式((从o在row.ItemArray中选择o.ToString())。ToArray())以加入表的每个DataRow,而不是再次循环,为了节省尽可能多的时间。

这是我的示例代码:

private string MakeHtmlTable(DataTable data)
{
            string[] table = new string[data.Rows.Count] ;
            long counter = 1;
            foreach (DataRow row in data.Rows)
            {
                table[counter-1] = "<tr><td>" + String.Join("</td><td>", (from o in row.ItemArray select o.ToString()).ToArray()) + "</td></tr>";

                counter+=1;
            }

            return "</br><table>" + String.Join("", table) + "</table>";
}

答案 4 :(得分:3)

来自this link

using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Text;
using System.Xml;

namespace ClientUtil
{
public class DataTableUtil
{

public static string DataTableToXmlString(DataTable dtData)
{
if (dtData == null || dtData.Columns.Count == 0)
return (string) null;
DataColumn[] primaryKey = dtData.PrimaryKey;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(“<TABLE>”);
stringBuilder.Append(“<TR>”);
foreach (DataColumn dataColumn in (InternalDataCollectionBase) dtData.Columns)
{
if (DataTableUtil.IsPrimaryKey(dataColumn.ColumnName, primaryKey))
stringBuilder.Append(“<TH IsPK=’true’ ColType='”).Append(Convert.ToString(dataColumn.DataType == typeof (object) ? (object) typeof (string) : (object) dataColumn.DataType)).Append(“‘>”).Append(dataColumn.ColumnName.Replace(“&”, “”)).Append(“</TH>”);
else
stringBuilder.Append(“<TH IsPK=’false’ ColType='”).Append(Convert.ToString(dataColumn.DataType == typeof (object) ? (object) typeof (string) : (object) dataColumn.DataType)).Append(“‘>”).Append(dataColumn.ColumnName.Replace(“&”, “”)).Append(“</TH>”);
}
stringBuilder.Append(“</TR>”);
int num1 = 0;
foreach (DataRow dataRow in (InternalDataCollectionBase) dtData.Rows)
{
stringBuilder.Append(“<TR>”);
int num2 = 0;
foreach (DataColumn dataColumn in (InternalDataCollectionBase) dtData.Columns)
{
string str = Convert.IsDBNull(dataRow[dataColumn.ColumnName]) ? (string) null : Convert.ToString(dataRow[dataColumn.ColumnName]).Replace(“<“, “&lt;”).Replace(“>”, “&gt;”).Replace(“\””, “&quot;”).Replace(“‘”, “&apos;”).Replace(“&”, “&amp;”);
if (!string.IsNullOrEmpty(str))
stringBuilder.Append(“<TD>”).Append(str).Append(“</TD>”);
else
stringBuilder.Append(“<TD>”).Append(“</TD>”);
++num2;
}
stringBuilder.Append(“</TR>”);
++num1;
}
stringBuilder.Append(“</TABLE>”);
return ((object) stringBuilder).ToString();
}

protected static bool IsPrimaryKey(string ColumnName, DataColumn[] PKs)
{
if (PKs == null || string.IsNullOrEmpty(ColumnName))
return false;
foreach (DataColumn dataColumn in PKs)
{
if (dataColumn.ColumnName.ToLower().Trim() == ColumnName.ToLower().Trim())
return true;
}
return false;
}

public static DataTable XmlStringToDataTable(string XmlData)
{
DataTable dataTable = (DataTable) null;
IList<DataColumn> list = (IList<DataColumn>) new List<DataColumn>();
if (string.IsNullOrEmpty(XmlData))
return (DataTable) null;
XmlDocument xmlDocument1 = new XmlDocument();
xmlDocument1.PreserveWhitespace = true;
XmlDocument xmlDocument2 = xmlDocument1;
xmlDocument2.LoadXml(XmlData);
XmlNode xmlNode1 = xmlDocument2.SelectSingleNode(“/TABLE”);
if (xmlNode1 != null)
{
dataTable = new DataTable();
int num = 0;
foreach (XmlNode xmlNode2 in xmlNode1.SelectNodes(“TR”))
{
if (num == 0)
{
foreach (XmlNode xmlNode3 in xmlNode2.SelectNodes(“TH”))
{
bool result = false;
string str = xmlNode3.Attributes[“IsPK”].Value;
if (!string.IsNullOrEmpty(str))
{
if (!bool.TryParse(str, out result))
result = false;
}
else
result = false;
Type type = Type.GetType(xmlNode3.Attributes[“ColType”].Value);
DataColumn column = new DataColumn(xmlNode3.InnerText, type);
if (result)
list.Add(column);
if (!dataTable.Columns.Contains(column.ColumnName))
dataTable.Columns.Add(column);
}
if (list.Count > 0)
{
DataColumn[] dataColumnArray = new DataColumn[list.Count];
for (int index = 0; index < list.Count; ++index)
dataColumnArray[index] = list[index];
dataTable.PrimaryKey = dataColumnArray;
}
}
else
{
DataRow row = dataTable.NewRow();
int index = 0;
foreach (XmlNode xmlNode3 in xmlNode2.SelectNodes(“TD”))
{
Type dataType = dataTable.Columns[index].DataType;
string s = xmlNode3.InnerText;
if (!string.IsNullOrEmpty(s))
{
try
{
s = s.Replace(“&lt;”, “<“);
s = s.Replace(“&gt;”, “>”);
s = s.Replace(“&quot;”, “\””);
s = s.Replace(“&apos;”, “‘”);
s = s.Replace(“&amp;”, “&”);
row[index] = Convert.ChangeType((object) s, dataType);
}
catch
{
if (dataType == typeof (DateTime))
row[index] = (object) DateTime.ParseExact(s, “yyyyMMdd”, (IFormatProvider) CultureInfo.InvariantCulture);
}
}
else
row[index] = Convert.DBNull;
++index;
}
dataTable.Rows.Add(row);
}
++num;
}
}
return dataTable;
}
}
}

答案 5 :(得分:1)

如果您使用Web窗体,那么网格视图可以很好地用于此

代码看起来有点像这样。

aspx页面。

<asp:GridView ID="GridView1" runat="server" DataKeyNames="Name,Size,Quantity,Amount,Duration"></asp:GridView>

您既可以手动输入数据,也可以使用代码端的源方法

public class Room
{
    public string Name
    public double Size {get; set;}
    public int Quantity {get; set;}
    public double Amount {get; set;}
    public int Duration {get; set;}
}

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)//this is so you can keep any data you want for the list
    {
        List<Room> rooms=new List<Room>();
        //then use the rooms.Add() to add the rooms you need.
        GridView1.DataSource=rooms
        GridView1.Databind()
    }
}

就我个人而言,我喜欢MVC4,客户端代码最终比Web Forms轻得多。它与使用类的上述示例类似,但您使用视图和Controller。

视图看起来像这样。

@model YourProject.Model.IEnumerable<Room>

<table>
    <th>
        <td>@Html.LabelFor(model => model.Name)</td>
        <td>@Html.LabelFor(model => model.Size)</td>
        <td>@Html.LabelFor(model => model.Quantity)</td>
        <td>@Html.LabelFor(model => model.Amount)</td>
        <td>@Html.LabelFor(model => model.Duration)</td>
   </th>
foreach(item in model)
{
    <tr>
        <td>@model.Name</td>
        <td>@model.Size</td>
        <td>@model.Quantity</td>
        <td>@model.Amount</td>
        <td>@model.Duration</td>
   </tr>
}
</table>

控制器可能看起来像这样。

public ActionResult Index()
{
    List<Room> rooms=new List<Room>();
    //again add the items you need

    return View(rooms);
}

希望这会有所帮助:)

答案 6 :(得分:1)

如果有人仍在寻找避免(在某种程度上)使用硬编码字符串的解决方案,您可以使用 HtmlTextWriter Nuget 包:

// NOTE: dt is the `DataTable` type object
StringBuilder sbControlHtml = new StringBuilder();
using (StringWriter stringWriter = new StringWriter())
{
    using HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Table);

    // add header row
    htmlWriter.RenderBeginTag(HtmlTextWriterTag.Tr);
    foreach(DataColumn col in dt.Columns)
    {
        htmlWriter.RenderBeginTag(HtmlTextWriterTag.Td);
        htmlWriter.Write(col.ColumnName);
        htmlWriter.RenderEndTag();
    }
    htmlWriter.RenderEndTag();

    // add rows
    foreach(DataRow row in dt.Rows)
    {
        htmlWriter.RenderBeginTag(HtmlTextWriterTag.Tr);
        foreach(DataColumn col in dt.Columns)
        {
            htmlWriter.RenderBeginTag(HtmlTextWriterTag.Td);
            htmlWriter.Write(row[col].ToString());
            htmlWriter.RenderEndTag();
        }
        htmlWriter.RenderEndTag();
    }
    
    htmlWriter.RenderEndTag();
    sbControlHtml.Append(stringWriter.ToString());
}

这个库的好处是支持.Net Standard。就我而言,我需要 .Net Core 替代 HtmlTextWriter,后者仅在 .Net Framework 上可用。我只是将这段代码放在 .Net Standard 项目中,然后从 .Net Core 中引用它。

答案 7 :(得分:0)

以防万一有人到达这里并希望使用VB(我这样做了,但我没有输入c#作为搜索词),这是第一个响应的基础。

Public Shared Function ConvertDataTableToHTML(dt As DataTable) As String
    Dim html As String = "<table>"
    html += "<tr>"
    For i As Integer = 0 To dt.Columns.Count - 1
        html += "<td>" + System.Web.HttpUtility.HtmlEncode(dt.Columns(i).ColumnName) + "</td>"
    Next
    html += "</tr>"
    For i As Integer = 0 To dt.Rows.Count - 1
        html += "<tr>"
        For j As Integer = 0 To dt.Columns.Count - 1
            html += "<td>" + System.Web.HttpUtility.HtmlEncode(dt.Rows(i)(j).ToString()) + "</td>"
        Next
        html += "</tr>"
    Next
    html += "</table>"
    Return html
End Function

答案 8 :(得分:0)

由于我在其他任何答案中都没有看到这一点,而且由于它更有效(在代码行和速度方面),这里是 VB.NET 中的解决方案,使用 stringbuilder 和 lambda 函数与 String.Join 代替列的 For 循环。

Dim sb As New StringBuilder
sb.Append("<table>")
sb.Append("<tr>" & String.Join("", dt.Columns.OfType(Of DataColumn)().Select(Function(x) "<th>" & x.ColumnName & "</th>").ToArray()) & "</tr>")
For Each row As DataRow In dt.Rows
    sb.Append("<tr>" & String.Join("", row.ItemArray.Select(Function(f) "<td>" & f.ToString() & "</td>")) & "</tr>")
Next
sb.Append("</table>")

你可以很容易地添加你自己的样式。

答案 9 :(得分:-1)

根据我的理解,您需要使用带有c#的asp.net在一个html表中显示3个表数据。

我认为最好只使用3个DataTable对象创建一个数据集。

在页面加载时直接将该数据集绑定到GriView。