Datatable to HTML Table

Datatable to html Table

use this function:

    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;
}

Converted c# datatable to HTML... how to add grid around the cells in HTML table?

Just add an inline style at the point at which you're generating the table cells.

sb.AppendFormat("<td style=\"border:solid 1px black\">{0}</td>", cellValue);

Creating HTML from a DataTable using C#

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("<html>");
sb.AppendLine(tab + "<body>");
sb.AppendLine(tab + tab + "<table>");

// headers.
sb.Append(tab + tab + tab + "<tr>");

foreach (DataColumn dc in dt.Columns)
{
sb.AppendFormat("<td>{0}</td>", dc.ColumnName);
}

sb.AppendLine("</tr>");

// data rows
foreach (DataRow dr in dt.Rows)
{
sb.Append(tab + tab + tab + "<tr>");

foreach (DataColumn dc in dt.Columns)
{
string cellValue = dr[dc] != null ? dr[dc].ToString() : "";
sb.AppendFormat("<td>{0}</td>", cellValue);
}

sb.AppendLine("</tr>");
}

sb.AppendLine(tab + tab + "</table>");
sb.AppendLine(tab + "</body>");
sb.AppendLine("</html>");

Display DataTable in HTML Table in ASP.Net C# Webform

If I had the points, I would have just made a comment but to fix your problem, all you need to do is comment out the following line:

PlaceHolder placeholder = new PlaceHolder();

The reason being is that, you have a PlaceHolder named placeholder on your markup, then create a completely new placeholder variable of Type PlaceHolder in the load code. Whilst they are named the same, the code considers them 2 completely different objects. See code below, also I borrowed someone else's code to create a datatable, since I don't have access to your db.

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
/*
Commented out because doing it this way creates
2 PlaceHolder variables named placeholder, everything else is as needed
*/
//PlaceHolder placeholder = new PlaceHolder();

//Populating a DataTable from database.
DataTable dt = this.GetData();
//Building an HTML string.
StringBuilder html = new StringBuilder();
//Table start.
html.Append("<table border = '1'>");
//Building the Header row.
html.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
html.Append("<th>");
html.Append(column.ColumnName);
html.Append("</th>");
}
html.Append("</tr>");
//Building the Data rows.
foreach (DataRow row in dt.Rows)
{
html.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
html.Append("<td>");
html.Append(row[column.ColumnName]);
html.Append("</td>");
}
html.Append("</tr>");
}
//Table end.
html.Append("</table>");
string strText = html.ToString();
////Append the HTML string to Placeholder.
placeholder.Controls.Add(new Literal { Text = html.ToString() });
}
}
private DataTable GetData()
{
// Modified your method, since I don't have access to your db, so I created one manually
// Here we create a DataTable with four columns.
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));

// Here we add five DataRows.
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
return table;
}

Download dataTable is printing HTML along with table

I had to change the UI function to get the proper attachment.

ui <- fluidPage(
img(src = "test.jpg", width = 170, height = 115, align = "left"),
tags$div(class = "header" , tags$h2("Cars", tags$br(), tags$h4("MTCARS", style = "text-align: center; color:navy;"), style = "text-align: center; color:navy;")),
dataTableOutput("table_output")
)

Get body of datatable as HTML element

For a more complex requirement like the one you have, you are going to need to combine DataTables capabilities with some extra logic (JavaScript, in this case) to iterate over the set of tables you need.

So, the following example is not a complete solution - it just shows how to create one copy of your original table, with an applied filter. But this could be extended to loop over each of your continents, one-by-one.

The code creates a variable called tableCopy which contains a clone of the original table. You can then use tableCopy.outerHTML to get the full HTML of the copied table.

$(document).ready(function() {

let table = $('#example').DataTable( {
// my test data is sourced from a JavaScript variable, not from ajax:
data: dataSet,
// my custom code will not work if deferRender is true:
"deferRender": false,
// for testing, provide pre-filtered data:
"search": {
"search": "ni"
},
columns: [
{ title: "ID", data: "id" },
{ title: "Name", data: "name" },
{ title: "Office", data: "office" },
{ title: "Position", data: "position" },
{ title: "Start date", data: "start_date" },
{ title: "Extn.", data: "extn" },
{ title: "Salary", data: "salary" }
]

} );

let tableCopy = document.getElementById("example").cloneNode(true);
tableCopy.id = 'my_copy'; // the cloned table needs a unique ID

//remove the (incomplete) set of <tr> nodes in the <tbody> node, since they
// only account for the initially displayed set of rows (one page of data):
$('tbody', tableCopy).empty();

// we will not select any rows which have been filtered out (and are therefore hidden):
let rowsSelector = { order: 'current', page: 'all', search: 'applied' };
// build a complete set of <tr> nodes using the DataTables API:
table.rows( rowsSelector ).every( function ( rowIdx, tableLoop, rowLoop ) {
$('tbody', tableCopy).append( this.node() );
} );

//console.log( tableCopy.outerHTML );

$('#displayTarget').html( tableCopy.outerHTML );

// redraw the main table to re-display the removed <tr> nodes:
table.draw( false );

} );

In your case, you would need to extend this approach to handle multiple copies of the table.

I have not tested the following - but this shows the approach:

  1. You would need an array of values to hold the copies:

    let tableCopies = [];
    contients.forEach(function (item, index) {
    tableCopies.push(document.getElementById("example").cloneNode(true));
    tableCopies[index].id = 'table_' + item; // e.g.: 'table_Europe'
    });

  2. You would need to extend this section:

table.rows( rowsSelector ).every( function ( rowIdx, tableLoop, rowLoop ) {
$('tbody', tableCopy).append( this.node() );
} );

Instead of using the filtered data from the original table, you would loop through every row - and you would not use the rowsSelector:

table.rows().every( ... )

In the body of that function, you would check which continent is in the current row:

table.rows( rowsSelector ).every( function ( rowIdx, tableLoop, rowLoop ) {
let continent = this.data().continent;
// and add the relevant continent row to the related object in the `tableCopies` array.
} );

DataTable limited rows

There is more than one option for this:

You can use the paging option and set it to false, or you can use the pageLength option to choose how many results you want to show on one page.

paging:

<script>
$(document).ready( function () {
$('#table_id').DataTable({
dom: 'B<"clear">lfrtip',
paging: false,
buttons: {
name: 'primary',
buttons: [ 'copy', 'csv', 'excel', 'pdf' ]
}
});
});
</script

pageLength:

<script>
$(document).ready( function () {
$('#table_id').DataTable({
"pageLength": 1000,
dom: 'B<"clear">lfrtip',
buttons: {
name: 'primary',
buttons: [ 'copy', 'csv', 'excel', 'pdf' ]
}
});
});
</script

How to convert a html components-based table to dash Datatable

Following up on the comments, as the code does not fit into comments box, I am copying the minimal code to create dash Datatable from a dataframe, from here, with minor changes to reflect your names

import dash
import dash_table
import pandas as pd

# here you would put the dataframe that features in your question as an argument to your function generate_table
df = dataframe

app = dash.Dash(__name__)

app.layout = dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict('records'),
)

if __name__ == '__main__':
app.run_server(debug=True)


Related Topics



Leave a reply



Submit