This post shows how to create a simple stylish table in a html file written to file using C#. Firstly, add a <style> section in the header that defines the table header and alternate row color scheme. Secondly, in each alternate row written specified the correct class id in the <tr> element. The follow code shows how it is done:
string[][] table = new string[3][];
table[0]=new string[3] {"10", "20", "30"};
table[1]=new string[3] {"11", "21", "31"};
table[2]=new string[3] {"12", "22", "32"};
using (StreamWriter writer = new StreamWriter(new FileStream(filename, FileMode.CreateNew, FileAccess.Write), Encoding.UTF8))
{
writer.WriteLine("<html>");
writer.WriteLine("<header>");
writer.WriteLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
writer.WriteLine(@"<style>
#customers
{
font-family:'Trebuchet MS', Arial, Helvetica, sans-serif;
width:100%;
border-collapse:collapse;
}
#customers td, #customers th
{
font-size:0.8em;
border:1px solid #98bf21;
padding:3px 7px 2px 7px;
}
#customers th
{
font-size:0.82em;
text-align:left;
padding-top:5px;
padding-bottom:4px;
background-color:#A7C942;
color:#ffffff;
}
#customers tr.alt td
{
color:#000000;
background-color:#EAF2D3;
}
#customers tr.nor td
{
background-color:white;
}
</style>
");
writer.WriteLine("</header>");
writer.WriteLine("<body>");
writer.WriteLine("<table id='customers' style='width:100%'>");
writer.WriteLine("<tr><th>Field1</th><th>Field2</th><th>Field3</th></tr>");
for (int line_index = 0; line_index < 3; ++line_index)
{
if (line_index % 2 == 0)
{
writer.WriteLine("<tr class='nor'>");
}
else
{
writer.WriteLine("<tr class='alt'>");
}
for (int column_index = 0; column_index < 3; ++column_index)
{
writer.WriteLine("<td>{0}</td>", table[line_index][colum_index]);
}
writer.WriteLine("</tr>");
}
writer.WriteLine("</table>");
writer.WriteLine("</body></html>");
writer.Flush();
}
No comments:
Post a Comment