Create an HTML table
You are encouraged to solve this task according to the task description, using any language you may know.
Create an HTML table.
- The table body should have at least three rows of three columns.
- Each of these three columns should be labelled "X", "Y", and "Z".
- An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
- The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
- The numbers should be aligned in the same fashion for all columns.
[edit] Ada
We define a generic package to output HTML tables:
with Ada.Strings.Unbounded;
generic
type Item_Type is private;
with function To_String(Item: Item_Type) return String is <>;
with procedure Put(S: String) is <>;
with procedure Put_Line(Line: String) is <>;
package HTML_Table is
subtype U_String is Ada.Strings.Unbounded.Unbounded_String;
function Convert(S: String) return U_String renames
Ada.Strings.Unbounded.To_Unbounded_String;
type Item_Array is array(Positive range <>, Positive range <>) of Item_Type;
type Header_Array is array(Positive range <>) of U_String;
procedure Print(Items: Item_Array; Column_Heads: Header_Array);
end HTML_Table;
The implementation of the package:
package body HTML_Table is
procedure Print(Items: Item_Array; Column_Heads: Header_Array) is
function Blanks(N: Natural) return String is
-- indention for better readable HTML
begin
if N=0 then
return "";
else
return " " & Blanks(N-1);
end if;
end Blanks;
procedure Print_Row(Row_Number: Positive) is
begin
Put(Blanks(4) & "<tr><td>" & Positive'Image(Row_Number) & "</td>");
for I in Items'Range(2) loop
Put("<td>" & To_String(Items(Row_Number, I)) & "</td>");
end loop;
Put_Line("</tr>");
end Print_Row;
procedure Print_Body is
begin
Put_Line(Blanks(2)&"<tbody align = ""right"">");
for I in Items'Range(1) loop
Print_Row(I);
end loop;
Put_Line(Blanks(2)&"</tbody>");
end Print_Body;
procedure Print_Header is
function To_Str(U: U_String) return String renames
Ada.Strings.Unbounded.To_String;
begin
Put_Line(Blanks(2) & "<thead align = ""right"">");
Put(Blanks(4) & "<tr><th></th>");
for I in Column_Heads'Range loop
Put("<td>" & To_Str(Column_Heads(I)) & "</td>");
end loop;
Put_Line("</tr>");
Put_Line(Blanks(2) & "</thead>");
end Print_Header;
begin
if Items'Length(2) /= Column_Heads'Length then
raise Constraint_Error with "number of headers /= number of columns";
end if;
Put_Line("<table>");
Print_Header;
Print_Body;
Put_Line("</table>");
end Print;
end HTML_Table;
Here is the main program, using an instance of HTML_Table:
with Ada.Text_IO, Ada.Numerics.Discrete_Random, HTML_Table;
procedure Test_HTML_Table is
-- define the Item_Type and the random generator
type Four_Digits is mod 10_000;
package Rand is new Ada.Numerics.Discrete_Random(Four_Digits);
Gen: Rand.Generator;
-- now we instantiate the generic package HTML_Table
package T is new HTML_Table
(Item_Type => Four_Digits,
To_String => Four_Digits'Image,
Put => Ada.Text_IO.Put,
Put_Line => Ada.Text_IO.Put_Line);
-- define the object that will the values that the table contains
The_Table: T.Item_Array(1 .. 4, 1..3);
begin
-- fill The_Table with random values
Rand.Reset(Gen);
for Rows in The_Table'Range(1) loop
for Cols in The_Table'Range(2) loop
The_Table(Rows, Cols) := Rand.Random(Gen);
end loop;
end loop;
-- output The_Table
T.Print(Items => The_Table,
Column_Heads => (T.Convert("X"), T.Convert("Y"), T.Convert("Z")));
end Test_HTML_Table;
Each time you run the program, you get different random values for the table. Here is a sample output:
<table>
<thead align = "right">
<tr><th></th><td>X</td><td>Y</td><td>Z</td></tr>
</thead>
<tbody align = "right">
<tr><td> 1</td><td> 7255</td><td> 3014</td><td> 9436</td></tr>
<tr><td> 2</td><td> 554</td><td> 3314</td><td> 8765</td></tr>
<tr><td> 3</td><td> 4832</td><td> 129</td><td> 2048</td></tr>
<tr><td> 4</td><td> 31</td><td> 6897</td><td> 8265</td></tr>
</tbody>
</table>
Viewing the output with Lynx:
X Y Z 1 7255 3014 9436 2 554 3314 8765 3 4832 129 2048 4 31 6897 8265
[edit] AutoHotkey
out = <table style="text-align:center; border: 1px solid"><th></th><th>X</th><th>Y</th><th>Z</th><tr>
Loop 4
out .= "`r`n<tr><th>" A_Index "</th><td>" Rand() "</td><td>" Rand() "</td><td>" Rand() "</tr>"
out .= "`r`n</table>"
MsgBox % clipboard := out
Rand(u=1000){
Random, n, 1, % u
return n
}
Output:
| X | Y | Z | |
|---|---|---|---|
| 1 | 289 | 556 | 43 |
| 2 | 102 | 100 | 971 |
| 3 | 582 | 295 | 264 |
| 4 | 396 | 762 | 633 |
[edit] AWK
#!/usr/bin/awk -f
BEGIN {
print "<table>\n <thead align = \"right\">";
printf " <tr><th></th><td>X</td><td>Y</td><td>Z</td></tr>\n </thead>\n <tbody align = \"right\">\n";
};
{
printf " <tr><td>%2i</td><td>%5i</td><td>%5i</td><td>%5i</td></tr>\n",NR,$1,$2,$3;
};
END {
print " </tbody>\n</table>\n";
};
[edit] BBC BASIC
Uses BBC BASIC's *spool command to create a file.
ncols% = 3
nrows% = 4
*spool temp.htm
PRINT "<html><head></head><body>"
PRINT "<table border=1 cellpadding=10 cellspacing=0>"
FOR row% = 0 TO nrows%
IF row% = 0 THEN
PRINT "<tr><th></th>" ;
ELSE
PRINT "<tr><th>" ; row% "</th>" ;
ENDIF
FOR col% = 1 TO ncols%
IF row% = 0 THEN
PRINT "<th>" CHR$(87 + col%) "</th>" ;
ELSE
PRINT "<td align=""right"">" ; RND(9999) "</td>" ;
ENDIF
NEXT col%
PRINT "</tr>"
NEXT row%
PRINT "</table>"
PRINT "</body></html>"
*spool
SYS "ShellExecute", @hwnd%, 0, "temp.htm", 0, 0, 1
Output:
<html><head></head><body> <table border=1 cellpadding=10 cellspacing=0> <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr> <tr><th>1</th><td align="right">2791</td><td align="right">8011</td><td align="right">9582</td> </tr> <tr><th>2</th><td align="right">6793</td><td align="right">6863</td><td align="right">4790</td> </tr> <tr><th>3</th><td align="right">8064</td><td align="right">2626</td><td align="right">3917</td> </tr> <tr><th>4</th><td align="right">2660</td><td align="right">8776</td><td align="right">6805</td> </tr> </table> </body></html>
[edit] C
#include <stdio.h>output (wiki doesn't like tbody/thead tags):
#include <stdlib.h>
int main()
{
int i;
printf("<table style=\"text-align:center; border: 1px solid\"><th></th>"
"<th>X</th><th>Y</th><th>Z</th>");
for (i = 0; i < 4; i++) {
printf("<tr><th>%d</th><td>%d</td><td>%d</td><td>%d</td></tr>", i,
rand() % 10000, rand() % 10000, rand() % 10000);
}
printf("</table>");
return 0;
}
| X | Y | Z | |
|---|---|---|---|
| 0 | 2777 | 886 | 9383 |
| 1 | 8335 | 7793 | 6915 |
| 2 | 6649 | 492 | 5386 |
| 3 | 27 | 2362 | 1421 |
[edit] C++
#include <fstream>
#include <boost/array.hpp>
#include <string>
#include <cstdlib>
#include <ctime>
#include <sstream>
void makeGap( int gap , std::string & text ) {
for ( int i = 0 ; i < gap ; i++ )
text.append( " " ) ;
}
int main( ) {
boost::array<char , 3> chars = { 'X' , 'Y' , 'Z' } ;
int headgap = 3 ;
int bodygap = 3 ;
int tablegap = 6 ;
int rowgap = 9 ;
std::string tabletext( "<html>\n" ) ;
makeGap( headgap , tabletext ) ;
tabletext += "<head></head>\n" ;
makeGap( bodygap , tabletext ) ;
tabletext += "<body>\n" ;
makeGap( tablegap , tabletext ) ;
tabletext += "<table>\n" ;
makeGap( tablegap + 1 , tabletext ) ;
tabletext += "<thead align=\"right\">\n" ;
makeGap( tablegap, tabletext ) ;
tabletext += "<tr><th></th>" ;
for ( int i = 0 ; i < 3 ; i++ ) {
tabletext += "<td>" ;
tabletext += *(chars.begin( ) + i ) ;
tabletext += "</td>" ;
}
tabletext += "</tr>\n" ;
makeGap( tablegap + 1 , tabletext ) ;
tabletext += "</thead>" ;
makeGap( tablegap + 1 , tabletext ) ;
tabletext += "<tbody align=\"right\">\n" ;
srand( time( 0 ) ) ;
for ( int row = 0 ; row < 5 ; row++ ) {
makeGap( rowgap , tabletext ) ;
std::ostringstream oss ;
tabletext += "<tr><td>" ;
oss << row ;
tabletext += oss.str( ) ;
for ( int col = 0 ; col < 3 ; col++ ) {
oss.str( "" ) ;
int randnumber = rand( ) % 10000 ;
oss << randnumber ;
tabletext += "<td>" ;
tabletext.append( oss.str( ) ) ;
tabletext += "</td>" ;
}
tabletext += "</tr>\n" ;
}
makeGap( tablegap + 1 , tabletext ) ;
tabletext += "</tbody>\n" ;
makeGap( tablegap , tabletext ) ;
tabletext += "</table>\n" ;
makeGap( bodygap , tabletext ) ;
tabletext += "</body>\n" ;
tabletext += "</html>\n" ;
std::ofstream htmltable( "testtable.html" , std::ios::out | std::ios::trunc ) ;
htmltable << tabletext ;
htmltable.close( ) ;
return 0 ;
}
Output ( of testtable.html ):
<html>
<head></head>
<body>
<table>
<thead align="right">
<tr><th></th><td>X</td><td>Y</td><td>Z</td></tr>
</thead>
<tbody align="right">
<tr><td>0<td>1274</td><td>6847</td><td>352</td></tr>
<tr><td>1<td>846</td><td>6577</td><td>4612</td></tr>
<tr><td>2<td>7543</td><td>1644</td><td>8143</td></tr>
<tr><td>3<td>4928</td><td>5714</td><td>8186</td></tr>
<tr><td>4<td>3436</td><td>7493</td><td>9344</td></tr>
</tbody>
</table>
</body>
</html>
[edit] C#
using System;
using System.Text;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
StringBuilder s = new StringBuilder();
Random rnd = new Random();
s.AppendLine("<table>");
s.AppendLine("<thead align = \"right\">");
s.Append("<tr><th></th>");
for(int i=0; i<3; i++)
s.Append("<td>" + "XYZ"[i] + "</td>");
s.AppendLine("</tr>");
s.AppendLine("</thead>");
s.AppendLine("<tbody align = \"right\">");
for( int i=0; i<3; i++ )
{
s.Append("<tr><td>"+i+"</td>");
for( int j=0; j<3; j++ )
s.Append("<td>"+rnd.Next(10000)+"</td>");
s.AppendLine("</tr>");
}
s.AppendLine("</tbody>");
s.AppendLine("</table>");
Console.WriteLine( s );
}
}
}
[edit] CoffeeScript
# This is one of many ways to create a table. CoffeeScript plays nice
# with any templating solution built for JavaScript, and of course you
# can build tables in the browser using DOM APIs. This approach is just
# brute force string manipulation.
table = (header_row, rows) ->
"""
<table>
#{header_row}
#{rows.join '\n'}
</table>
"""
tr = (cells) -> "<tr>#{cells.join ''}</tr>"
th = (s) -> "<th align='right'>#{s}</th>"
td = (s) -> "<td align='right'>#{s}</td>"
rand_n = -> Math.floor Math.random() * 10000
header_cols = ['', 'X', 'Y', 'Z']
header_row = tr (th s for s in header_cols)
rows = []
for i in [1..5]
rows.push tr [
th(i)
td rand_n()
td rand_n()
td rand_n()
]
html = table header_row, rows
console.log html
output:
| X | Y | Z | |
|---|---|---|---|
| 1 | 1575 | 7445 | 4544 |
| 2 | 3827 | 5029 | 235 |
| 3 | 10 | 9363 | 4381 |
| 4 | 297 | 2463 | 5745 |
| 5 | 4063 | 6726 | 1093 |
[edit] D
import std.stdio, std.random;
void main() {
writeln(`<table style="text-align:center; border: 1px solid">`);
writeln("<th></th><th>X</th><th>Y</th><th>Z</th>");
foreach (i; 0 .. 4)
writefln("<tr><th>%d</th><td>%d</td><td>%d</td><td>%d</td></tr>",
i, uniform(0,1000), uniform(0,1000), uniform(0,1000));
writeln("</table>");
}
Output:
| X | Y | Z | |
|---|---|---|---|
| 0 | 524 | 739 | 847 |
| 1 | 13 | 813 | 782 |
| 2 | 926 | 580 | 663 |
| 3 | 309 | 816 | 750 |
[edit] Delphi
program CreateHTMLTable;
{$APPTYPE CONSOLE}
uses SysUtils;
function AddTableRow(aRowNo: Integer): string;
begin
Result := Format(' <tr><td>%d</td><td>%d</td><td>%d</td><td>%d</td></tr>',
[aRowNo, Random(10000), Random(10000), Random(10000)]);
end;
var
i: Integer;
begin
Randomize;
Writeln('<table>');
Writeln(' <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>');
for i := 1 to 4 do
Writeln(AddTableRow(i));
Writeln('</table>');
Readln;
end.
Output:
<table>
<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>
<tr><td>1</td><td>7371</td><td>2659</td><td>1393</td></tr>
<tr><td>2</td><td>6710</td><td>5025</td><td>5203</td></tr>
<tr><td>3</td><td>1316</td><td>1599</td><td>2086</td></tr>
<tr><td>4</td><td>4785</td><td>6612</td><td>5042</td></tr>
</table>
[edit] Euphoria
puts(1,"<table>\n")
puts(1," <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>\n")
for i = 1 to 3 do
printf(1," <tr><td>%d</td>",i)
for j = 1 to 3 do
printf(1,"<td>%d</td>",rand(10000))
end for
puts(1,"</tr>\n")
end for
puts(1,"</table>")
Sample output:
<table>
<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>
<tr><td>1</td><td>7978</td><td>7376</td><td>2382</td></tr>
<tr><td>2</td><td>3632</td><td>1947</td><td>8900</td></tr>
<tr><td>3</td><td>4098</td><td>1563</td><td>2762</td></tr>
</table>
[edit] Go
html/template is a package in the standard library.
package main
import (
"fmt"
"os"
"html/template"
)
type Row struct {
X, Y, Z int
}
var tmpl = `<table>
<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>
{{range $ix, $row := .}} <tr><td>{{$ix}}</td><td>{{$row.X}}</td><td>{{$row.Y}}</td><td>{{$row.Z}}</td></tr>
{{end}}</table>
`
func main() {
// create template
ct := template.Must(template.New("").Parse(tmpl))
// make up data
data := make([]Row, 4)
for r := range data {
data[r] = Row{r * 3, r*3 + 1, r*3 + 2}
}
// open output file
hf, err := os.Create("table.html")
if err != nil {
fmt.Println(err)
return
}
defer hf.Close()
// apply template to data
if err := ct.Execute(hf, data); err != nil {
fmt.Println(err)
}
}
Output in table.html:
<table>
<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>
<tr><td>0</td><td>0</td><td>1</td><td>2</td></tr>
<tr><td>1</td><td>3</td><td>4</td><td>5</td></tr>
<tr><td>2</td><td>6</td><td>7</td><td>8</td></tr>
<tr><td>3</td><td>9</td><td>10</td><td>11</td></tr>
</table>
[edit] Groovy
import groovy.xml.MarkupBuilder
def createTable(columns, rowCount) {
def writer = new StringWriter()
new MarkupBuilder(writer).table(style: 'border:1px solid;text-align:center;') {
tr {
th()
columns.each { title -> th(title)}
}
(1..rowCount).each { row ->
tr {
td(row)
columns.each { td((Math.random() * 9999) as int ) }
}
}
}
writer.toString()
}
println createTable(['X', 'Y', 'Z'], 3)
Output:
| X | Y | Z | |
|---|---|---|---|
| 1 | 6106 | 9898 | 1584 |
| 2 | 1641 | 9387 | 3858 |
| 3 | 8970 | 4843 | 681 |
[edit] Icon and Unicon
procedure main()Sample Output:
printf("<table>\n <tr><th></th><th>X</th><th>Y</th><th>Z</th>")
every r := 1 to 4 do {
printf("</tr>\n <tr><td>%d</td>",r)
every 1 to 3 do printf("<td>%d</td>",?9999) # random 4 digit numbers per cell
}
printf("</tr>\n</table>\n")
end
link printf
<table>
<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>
<tr><td>1</td><td>3129</td><td>3294</td><td>7013</td></tr>
<tr><td>2</td><td>5045</td><td>169</td><td>5761</td></tr>
<tr><td>3</td><td>7001</td><td>963</td><td>4183</td></tr>
<tr><td>4</td><td>1695</td><td>1158</td><td>1240</td></tr>
</table>
[edit] J
We can define:
ele=:4 :0
nm=. x-.LF
lf=. x-.nm
;('<',nm,'>') ,L:0 y ,L:0 '</',nm,'>',lf
)
hTbl=:4 :0
rows=. 'td' <@ele"1 ":&.>y
'table' ele ('tr',LF) <@ele ('th' ele x); rows
)
With these definitions:
('';;:'X Y Z') hTbl ":&.>(i.5),.i.5 3
<table><tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>
<tr><td>0</td><td>0</td><td>1</td><td>2</td></tr>
<tr><td>1</td><td>3</td><td>4</td><td>5</td></tr>
<tr><td>2</td><td>6</td><td>7</td><td>8</td></tr>
<tr><td>3</td><td>9</td><td>10</td><td>11</td></tr>
<tr><td>4</td><td>12</td><td>13</td><td>14</td></tr>
</table>
Or, if running under jhs:
jhtml ('';;:'X Y Z') hTbl ":&.>(i.5),.i.5 3
to display the table inline, as html.
[edit] Java
This example assumes the header row is the first row in the given array and does not add row numbers. They will need to be added by the programmer when constructing the array.
public class HTML {
public static String array2HTML(Object[][] array){
StringBuilder html = new StringBuilder(
"<table>");
for(Object elem:array[0]){
html.append("<th>" + elem.toString() + "</th>");
}
for(int i = 1; i < array.length; i++){
Object[] row = array[i];
html.append("<tr>");
for(Object elem:row){
html.append("<td>" + elem.toString() + "</td>");
}
html.append("</tr>");
}
html.append("</table>");
return html.toString();
}
public static void main(String[] args){
Object[][] ints = {{"","X","Y","Z"},{1,1,2,3},{2,4,5,6},{3,7,8,9},{4,10,11,12}};
System.out.println(array2HTML(ints));
}
}
Output:
<table><th></th><th>X</th><th>Y</th><th>Z</th><tr><td>1</td><td>1</td><td>2</td><td>3</td></tr><tr><td>2</td><td>4</td><td>5</td><td>6</td></tr><tr><td>3</td><td>7</td><td>8</td><td>9</td></tr><tr><td>4</td><td>10</td><td>11</td><td>12</td></tr></table>
[edit] JavaScript
<html><head><title>Table maker</title><script type="application/javascript">
// normally, don't do this: at least name it something other than "a"
Node.prototype.a = function (e) { this.appendChild(e); return this }
function ce(tag, txt) {
var x = document.createElement(tag);
x.textContent = (txt === undefined) ? '' : txt;
return x;
}
function make_table(cols, rows) {
var tbl = ce('table', ''), tr = ce('tr'), th;
tbl.a(tr.a(ce('th')));
var z = 'Z'.charCodeAt(0);
for (var l = z - cols + 1; l <= z; l++)
tr.a(ce('th', String.fromCharCode(l)));
for (var r = 1; r <= rows; r++) {
tbl.a(tr = ce('tr').a(ce('th', r)));
for (var c = 0; c < cols; c++)
tr.a(ce('td', Math.floor(Math.random() * 10000)));
}
document.body
.a(ce('style',
'td, th {border: 1px solid #696;' +
'padding:.4ex} td {text-align: right }' +
'table { border-collapse: collapse}'))
.a(tbl);
}
</script></head>
<body><script>make_table(5, 4)</script></body></html>
[edit] Liberty BASIC
This creates and saves an html file, then calls web browser to display it.
A time delay is needed to allow this, then the file is deleted.
nomainwin
quote$ =chr$( 34)
html$ ="<html><head></head><body>"
html$ =html$ +"<table border =" +quote$ +"6"+ quote$ +" solid rules =none ; cellspacing =" +quote$ +"10" +quote$ +"> <th> </th> <th> X </th> <th> Y </th> <th> Z </th>"
for i =1 to 4
d1$ =str$( i)
d2$ =str$( int( 10000 *rnd( 1)))
d3$ =str$( int( 10000 *rnd( 1)))
d4$ =str$( int( 10000 *rnd( 1)))
html$ =html$ +"<tr align ="; quote$; "right"; quote$; "> <th>"; d1$; " </th> <td>" +d2$ +" </td> <td>" +d3$ +" </td> <td>" +d4$ +" </td> </tr>"
next i
html$ =html$ +"</table>"
html$ =html$ +"</body></html>"
open "table.html" for output as #o
#o html$;
close #o
address$ ="table.html"
run "explorer.exe "; address$
timer 5000, [on]
wait
[on]
timer 0
kill "table.html"
wait
sub quit w$
close #w$
end
end sub
[edit] Mathematica
x := RandomInteger[10];
Print["<table>", "\n","<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>"]
Scan[Print["<tr><td>", #, "</td><td>", x, "</td><td>", x, "</td><td>","</td></tr>"] & , Range[3]]
Print["</table>"]
Output :
<table> <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr> <tr><td>1</td><td>6</td><td>10</td><td></td></tr> <tr><td>2</td><td>1</td><td>10</td><td></td></tr> <tr><td>3</td><td>6</td><td>7</td><td></td></tr> </table>
[edit] MATLAB / Octave
function htmltable(fid,table,Label)
fprintf(fid,'<table>\n <thead align = "right">\n');
if nargin<3,
fprintf(fid,' <tr><th></th><td>X</td><td>Y</td><td>Z</td></tr>\n </thead>\n <tbody align = "right">\n');
else
fprintf(fid,' <tr><th></th>');
fprintf(fid,'<td>%s</td>',Label{:});
fprintf(fid,'</tr>\n </thead>\n <tbody align = "right">\n');
end;
fprintf(fid,' <tr><td>%2i</td><td>%5i</td><td>%5i</td><td>%5i</td></tr>\n', [1:size(table,1);table']);
fprintf(fid,' </tbody>\n</table>\n');
end
Output:
>> htmltable(1,ceil(rand(5,3)*10000))
<table>
<thead align = "right">
<tr><th></th><td>X</td><td>Y</td><td>Z</td></tr>
</thead>
<tbody align = "right">
<tr><td> 1</td><td> 6639</td><td> 1110</td><td> 296</td></tr>
<tr><td> 2</td><td> 4864</td><td> 1252</td><td> 8412</td></tr>
<tr><td> 3</td><td> 3800</td><td> 4556</td><td> 3752</td></tr>
<tr><td> 4</td><td> 5728</td><td> 6897</td><td> 2157</td></tr>
<tr><td> 5</td><td> 2272</td><td> 8503</td><td> 7021</td></tr>
</tbody>
</table>
[edit] Modula-2
MODULE testCGI;
FROM InOut IMPORT WriteCard, WriteLn, WriteString, WriteBf;
FROM Arguments IMPORT ArgTable, GetEnv;
FROM Strings IMPORT Assign, Length, String;
VAR EnvVars : ArgTable;
PROCEDURE ReadEnvVar;
VAR Value : String;
i : CARDINAL;
BEGIN
WriteString ('<table border="1" cellpadding="4" width="80%" align="center">');
WriteString ('<tr><th>Index</th><th>Length</th><th>Content</th></tr>');
i := 0;
LOOP
IF EnvVars^ [i] = NIL THEN EXIT END;
Assign (Value, EnvVars^ [i]^);
WriteString ('<tr><td align="center">');
WriteCard (i, 2);
WriteString ('</td><td align="center">');
WriteCard (Length (Value), 3);
WriteString ('</td><td>'); WriteString (Value);
WriteString ("</td></tr>");
WriteLn;
INC (i)
END;
WriteString("</table>");
END ReadEnvVar;
BEGIN
GetEnv (EnvVars);
WriteString ('Content-type:text/html');
WriteLn;
WriteLn;
WriteString ('<html><head>');
WriteString ('<title>CGI with the Mocka Modula-2 compiler</title>');
WriteString ('</head><body>');
WriteLn;
WriteString ('<center><h2>CGI environment passed along by your browser</h2></center><p>');
ReadEnvVar;
WriteString ('</body></html>');
WriteLn;
WriteBf
END testCGI.
[edit] NewLISP
; file: html-table.lsp
; url: http://rosettacode.org/wiki/Create_an_HTML_table
; author: oofoe 2012-01-29
(seed (time-of-day)) ; Initialize random number generator.
; The "tab" variable tracks the HTML indent. "pad" composes a line
; with the appropriate indent and a terminal newline.
(setq tab 0)
(define (pad text) (string (dup " " tab) text "\n"))
; NewLISP allows almost any character in an identifier, so I can name
; my functions after the HTML elements they invoke. This one formats a
; single table data cell.
(define (<td> text) (pad (string "<td>" text "</td>")))
; "<tr>" will accept either a number of arguments, each one to be
; formatted as a table cell, or a single list argument, which is
; broken into table cells. For convenience, I format each list item
; with the "<td>" function so I can feed it raw lists.
(define (<tr>)
(let ((data (args))
(s (pad "<tr>")))
(if (list? (data 0)) (setq data (data 0)))
(inc tab)
(dolist (el data) (extend s (<td> el)))
(dec tab)
(extend s (pad "</tr>"))
s))
; By defining "<table>" as a macro, I ensure that the rows won't be
; evaluated until I've got the table started, which preserves the
; formatting.
(define-macro (<table>)
(let ((s (pad "<table>")))
(inc tab) (doargs (row) (extend s (eval row))) (dec tab)
(extend s (pad "</table>"))
s
))
; Test
(print (<table> (<tr> "" "X" "Y" "Z")
(<tr> (cons 0 (rand 1000 3)))
(<tr> (cons 1 (rand 1000 3)))
(<tr> (cons 2 (rand 1000 3)))
))
(exit)
Sample output:
<table>
<tr>
<td></td>
<td>X</td>
<td>Y</td>
<td>Z</td>
</tr>
<tr>
<td>0</td>
<td>289</td>
<td>824</td>
<td>462</td>
</tr>
<tr>
<td>1</td>
<td>49</td>
<td>600</td>
<td>84</td>
</tr>
<tr>
<td>2</td>
<td>511</td>
<td>219</td>
<td>742</td>
</tr>
</table>
Table:
| X | Y | Z | |
| 0 | 289 | 824 | 462 |
| 1 | 49 | 600 | 84 |
| 2 | 511 | 219 | 742 |
[edit] OCaml
A simple printf method:
let () =
let buf = Buffer.create 1 in
let s = Buffer.add_string buf in
Random.self_init();
s "<table>";
s "<thead align=\"right\">";
s "<tr><th></th>";
List.iter (fun v ->
s ("<td>" ^ v ^ "</td>")
) ["X"; "Y"; "Z"];
s "</tr>";
s "</thead>";
s "<tbody align=\"right\">";
for i = 0 to pred 3 do
s ("<tr><td>" ^ string_of_int i ^ "</td>");
for j = 0 to pred 3 do
s ("<td>" ^ string_of_int (Random.int 1000) ^ "</td>");
done;
s "</tr>";
done;
s "</tbody>";
s "</table>";
print_endline (Buffer.contents buf)
[edit] With a dedicated library
Using the library ocaml-xhtml. With this library the validity of the pages is guaranteed by the OCaml type system.
open XHTML.M_01_01
let _td s = td [pcdata s]
let _th s = th [pcdata s]
let my_table =
table ~a:[a_border 1]
(tr
(_th "") [
(_th "X");
(_th "Y");
(_th "Z")]
)
[
(tr
(_td "1") [
(_td "aa");
(_td "bb");
(_td "cc")]
);
(tr
(_td "2") [
(_td "dd");
(_td "ee");
(_td "ff")]
);
]
let my_page =
html
(head (title (pcdata "My Page")) [])
(body
[ h1 [pcdata "My Table"];
my_table;
]
)
let () =
pretty_print ~width:80 print_string my_page
[edit] TyXml
The library TyXml contains a module for XHTML that provides the same interface than the previous ocaml-xhtml library.
#use "topfind"
#require "tyxml"
module X = XHTML.M_01_01 (* XHTML 1.1 *)
module P = XHTML.P_01_01
let make_table () =
let td1 = X.td [X.pcdata "1"] in
let td2 = X.td [X.pcdata "2"] in
let td3 = X.td [X.pcdata "3"] in
let my_tr = X.tr td1 [td2; td3] in
let my_table = X.table my_tr [] in
(my_table)
let () =
let my_title = X.title (X.pcdata "My Page") in
let my_head = X.head my_title [] in
let my_h1 = X.h1 [X.pcdata "My Table"] in
let my_table = make_table () in
let my_body = X.body [my_h1; my_table] in
let my_html = X.html my_head my_body in
P.print print_endline my_html;
;;
The previous function make_table () produces a simple table, we can replace it by the function below to output a more complex table with thead and tbody:
let make_table () =
let br = X.a_border 1 in
let th s = X.th [X.pcdata s] in
let td s = X.td [X.pcdata s] in
let my_thead = X.thead (X.tr (th "") [th "X"; th "Y"; th "Z"]) [] in
let my_tr1 = X.tr (td "1") [td "AAA"; td "BBB"; td "CCC"] in
let my_tr2 = X.tr (td "2") [td "DDD"; td "EEE"; td "FFF"] in
let my_tr3 = X.tr (td "3") [td "GGG"; td "HHH"; td "III"] in
let my_tbody = X.tbody my_tr1 [my_tr2; my_tr3] in
let my_table = X.tablex ~thead:my_thead ~a:[br] my_tbody [] in
(my_table)
[edit] Oz
As a complete web application, using the "Roads" web programming library. Connect your browser to http://localhost:8080/table after starting the program.
declare
[Roads] = {Module.link ['x-ozlib://wmeyer/roads/Roads.ozf']}
fun {Table Session}
html(
head(title("Show a table with row and column headings")
style(type:"text/css"
css(td 'text-align':center)
))
body(
{TagFromList table
tr(th th("X") th("Y") th("Z"))
|
{CreateRows 3 5}
}))
end
fun {CreateRows NumCols NumRows}
{List.map {List.number 1 NumRows 1}
fun {$ Row}
{TagFromList tr
td( {Int.toString Row} )
|
{List.map {List.number 1 NumCols 1}
fun {$ Col}
SequentialNumber = (Row-1)*NumCols + Col
in
td( {Int.toString SequentialNumber} )
end
}}
end
}
end
TagFromList = List.toTuple
in
{Roads.registerFunction table Table}
{Roads.run}
[edit] PARI/GP
html(n=3)={
print("<table>\n<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>");
for(i=1,n,
print1("<tr><td>"i"</td>");
for(j=1,3,print1("<td>"random(9999)"</td>"));
print("</tr>")
);
print("</table>")
};
Output:
<table> <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr> <tr><td>1</td><td>6055</td><td>6794</td><td>6034</td></tr> <tr><td>2</td><td>8930</td><td>1992</td><td>7087</td></tr> <tr><td>3</td><td>9592</td><td>5836</td><td>7980</td></tr> </table>
Note also the built-in printtex command, which allows the analogous task to be written as
printtex(matrix(4,4,i,j,if(i==1,if(j==1,"",Strchr(86+j)),if(j==1,i,random(9999)))))
[edit] Pascal
See Delphi
[edit] Perl
my @heading = qw(X Y Z);
my $rows = 5;
print '<table><thead><td>',
(map { "<th>$_</th>" } @heading),
"</thead><tbody>";
for (1 .. $rows) {
print "<tr><th>$_</th>",
(map { "<td>".int(rand(10000))."</td>" } @heading),
"</tr>";
}
print "</tbody></table>";
Note that this is a rather inane way (because of the inane task specification) of generating structured document. For serious work, one should use a module such as XML or HTML for well-formedness instead of this ad hoc method.
[edit] Perl 6
This is certainly not the only or best way to generate HTML tables using Perl 6; just an example of one possible method.
my @header = < X Y Z>;
my $rows = 5;
sub tag ($tag, $string, $param?) { return "<$tag" ~ ($param ?? " $param" !! '') ~ ">$string" ~ "</$tag>" };
my $table = tag('tr', ( tag('th', $_) for @header));
for 1 .. $rows -> $row {
$table ~= tag('tr', ( tag('td', $row, 'align="right"')
~ (tag('td', (^10000).pick, 'align="right"') for 1..^@header)));
}
say tag('table', $table, 'cellspacing=4 style="text-align:right; border: 1px solid;"');
Sample output:
| X | Y | Z | |
|---|---|---|---|
| 1 | 2179 | 4778 | 2717 |
| 2 | 2160 | 1592 | 4348 |
| 3 | 4511 | 540 | 7187 |
| 4 | 3484 | 5882 | 1273 |
| 5 | 1310 | 4017 | 410 |
[edit] PicoLisp
(load "@lib/xhtml.l")
(<table> NIL NIL '(NIL (NIL "X") (NIL "Y") (NIL "Z"))
(for N 3
(<row> NIL N 124 456 789) ) )
[edit] PL/I
/* Create an HTML table. 6/2011 */
create: procedure options (main);
create_table: procedure (headings, table_contents);
declare headings(*) character (10) varying;
declare table_contents(*, *) fixed;
declare (i, row, col) fixed;
put skip edit ('<table>') (a);
/* Headings. */
put skip edit ('<tr><th></th> ') (a);
/* For an empty column heading */
do i = 1 to hbound(headings);
put edit ('<th>', headings(i), '</th> ' ) (a);
end;
put edit ('</tr>') (a);
/* Table contents. */
do row = 1 to hbound(table_contents, 1);
/* row number */
put skip edit ('<tr><td>', row, '</td> ') (a);
/* row contents */
do col = 1 to hbound(table_contents, 2);
put edit ('<td>', table_contents(row, col), '</td> ' ) (a);
end;
put edit ('</tr>') (a);
end;
put skip edit ('</table>' ) (a);
end create_table;
declare headings (3) character (1) static initial ('X', 'Y', 'Z');
declare table_contents(3, 3) fixed static initial (
4, -3, 8,
7, 2, -6,
11, 1, 15);
call create_table (headings, table_contents);
end create;
[edit] Protium
Opcodes of interest: SDC -- simple document; R!I -- ranged random integer
<@ SDCLIT>
<@ DTBLIT>
<@ DTRLITLIT>
<@ DTDLITLIT>|[style]background-color:white</@>
<@ DTD>X</@>
<@ DTD>Y</@>
<@ DTD>Z</@>|[style]width:100%; background-color:brown;color:white; text-align:center</@>
<@ ITEFORLIT>10|
<@ DTRLITCAP>
<@ DTDPOSFORLIT>...|[style]background-color:Brown; color:white; text-align:right</@>
<@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@>
<@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@>
<@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@>
|[style]background-color:white;color:black</@>
</@>
</@>
|Number Table</@>
[edit] Python
import random
def rand9999():
return random.randint(1000, 9999)
def tag(attr='', **kwargs):
for tag, txt in kwargs.items():
return '<{tag}{attr}>{txt}</{tag}>'.format(**locals())
if __name__ == '__main__':
header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\n'
rows = '\n'.join(tag(tr=''.join(tag(' style="font-weight: bold;"', td=i)
+ ''.join(tag(td=rand9999())
for j in range(3))))
for i in range(1, 6))
table = tag(table='\n' + header + rows + '\n')
print(table)
Sample output
| X | Y | Z | |
|---|---|---|---|
| 1 | 6040 | 4697 | 7055 |
| 2 | 2525 | 5468 | 6901 |
| 3 | 8851 | 3727 | 8379 |
| 4 | 5313 | 4396 | 1765 |
| 5 | 4013 | 5924 | 6082 |
The raw HTML
<table>
<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>
<tr><td style="font-weight: bold;">1</td><td>6040</td><td>4697</td><td>7055</td></tr>
<tr><td style="font-weight: bold;">2</td><td>2525</td><td>5468</td><td>6901</td></tr>
<tr><td style="font-weight: bold;">3</td><td>8851</td><td>3727</td><td>8379</td></tr>
<tr><td style="font-weight: bold;">4</td><td>5313</td><td>4396</td><td>1765</td></tr>
<tr><td style="font-weight: bold;">5</td><td>4013</td><td>5924</td><td>6082</td></tr>
</table>
[edit] Rascal
import IO;
import util::Math;
str html(str title, str content) = item("html", item("title", title) + item("body", content));
str item(str op, str content) = "\<<op>\><content>\</<op>\>";
str table(str content) = item("table border=\"0\"", content);
str tr(str content) = item("tr", content);
str td(str content) = item("td", content);
public str generateTable(int rows){
int i(){return arbInt(10000);};
rows = (tr(td("")+td("X")+td("Y")+td("Z"))
| it + tr(td("<x>")+td("<i()>")+td("<i()>")+td("<i()>"))
| x <- [1..rows]);
writeFile(|file:///location|,
html("Rosetta Code Table", table(rows)));
return "written";
}
This will result in a simple html file. For example:
rascal>generateTable(10)
str: "written"
has as output:
<html><title>Rosetta Code Table</title><body><table border="0"><tr><td></td><td>X</td><td>Y</td><td>Z</td></tr><tr><td>1</td><td>253</td><td>3988</td><td>3208</td></tr><tr><td>2</td><td>315</td><td>2014</td><td>47</td></tr><tr><td>3</td><td>749</td><td>3379</td><td>1076</td></tr><tr><td>4</td><td>241</td><td>3211</td><td>1848</td></tr><tr><td>5</td><td>1</td><td>1605</td><td>6469</td></tr><tr><td>6</td><td>599</td><td>1243</td><td>1189</td></tr><tr><td>7</td><td>741</td><td>4709</td><td>2854</td></tr><tr><td>8</td><td>918</td><td>482</td><td>7160</td></tr><tr><td>9</td><td>451</td><td>572</td><td>6229</td></tr><tr><td>10</td><td>955</td><td>7970</td><td>9684</td></tr></table border="0"></body></html>
which results in:
[edit] Retro
Using the casket::html' library which allows creation of HTML using quotes and combinators:
needs casket::html'
with casket::html'
: rnd ( -$ ) random 1000 mod toString ;
[ [ [ ] td [ "x" ] td [ "y" ] td [ "z" ] td ] tr
[ [ "1" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
[ [ "2" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
[ [ "3" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
[ [ "4" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
[ [ "5" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
[ [ "6" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
] table
[edit] REXX
The LINEOUTs (writes to a file) for the various HTML tags were broken up into seperate pieces which
makes reading the file easier and also helps in debugging, but they could've been combined into a
single LINEOUT for succinctness.
/*REXX program to create an HTML table of five rows and three columns. */
arg rows .; if rows=='' then rows=5 /*no ROWS specified? Use default*/
cols=3
maxRand=9999 /*4-digit numbers, allow negative*/
headerInfo='X Y Z' /*column header information. */
oFID='a_table.html'
call lineout oFid,"<html>"
call lineout oFid,"<head></head>"
call lineout oFid,"<body>"
call lineout oFid,"<table border=5 cellpadding=20 cellspace=0>"
do r=0 to rows
if r==0 then call lineout oFid,"<tr><th></th>"
else call lineout oFid,"<tr><th>" r "</th>"
do c=1 for cols
if r==0 then call lineout oFid,"<th>" word(headerInfo,c) "</th>"
else call lineout oFid,"<td align=right>" rnd() "</td>"
end /*c*/
end /*r*/
call lineout oFid,"</table>"
call lineout oFid,"</body>"
call lineout oFid,"</html>"
exit
/*─────────────────────────────────────RND subroutine───────────────────*/
/*subroutine was subroutinized for better viewabilityness.*/
rnd: return right(random(0,maxRand*2)-maxRand,5) /*REXX doesn't gen negs*/
Output generated (written to a file) when using the default input
<html> <head></head> <body> <table border=5 cellpadding=20 cellspace=0> <tr><th></th> <th> X </th> <th> Y </th> <th> Z </th> <tr><th> 1 </th> <td align=right> -1517 </td> <td align=right> 5513 </td> <td align=right> -7697 </td> <tr><th> 2 </th> <td align=right> 8373 </td> <td align=right> 142 </td> <td align=right> -3641 </td> <tr><th> 3 </th> <td align=right> -3971 </td> <td align=right> -717 </td> <td align=right> 5390 </td> <tr><th> 4 </th> <td align=right> 9727 </td> <td align=right> -2023 </td> <td align=right> -2536 </td> <tr><th> 5 </th> <td align=right> -6093 </td> <td align=right> -7179 </td> <td align=right> 642 </td> </table> </body> </html>
Rendered output
| X | Y | Z | |
|---|---|---|---|
| 1 | -1517 | 5513 | -7697 |
| 2 | 8373 | 142 | -3641 |
| 3 | -3971 | -717 | 5390 |
| 4 | 9727 | -2023 | -2536 |
| 5 | -6093 | -7179 | 642 |
[edit] Ruby
Pure Ruby solution:
def r
rand(10000)
end
STDOUT << "".tap do |html|
html << "<table>"
[
['X', 'Y', 'Z'],
[r ,r ,r],
[r ,r ,r],
[r ,r ,r],
[r ,r ,r]
].each_with_index do |row, index|
html << "<tr>"
html << "<td>#{index > 0 ? index : nil }</td>"
html << row.map { |e| "<td>#{e}</td>"}.join
html << "</tr>"
end
html << "</table>"
end
This creates a plain HTML table, without any CSS to draw borders or to set column widths.
def r; rand(10000); endOutput:
table = [["", "X", "Y", "Z"],
[ 1, r, r, r],
[ 2, r, r, r],
[ 3, r, r, r]]
require 'rexml/document'
xtable = REXML::Element.new("table")
table.each do |row|
xrow = REXML::Element.new("tr", xtable)
row.each do |cell|
xcell = REXML::Element.new("td", xrow)
REXML::Text.new(cell.to_s, false, xcell)
end
end
formatter = REXML::Formatters::Pretty.new
formatter.compact = true
formatter.write(xtable, $stdout)
<table>
<tr>
<td></td>
<td>X</td>
<td>Y</td>
<td>Z</td>
</tr>
<tr>
<td>1</td>
<td>1358</td>
<td>6488</td>
<td>6434</td>
</tr>
<tr>
<td>2</td>
<td>2477</td>
<td>6493</td>
<td>1330</td>
</tr>
<tr>
<td>3</td>
<td>240</td>
<td>3038</td>
<td>9849</td>
</tr>
</table>
[edit] Run BASIC
html "<table border=1><tr align=center><td>Row</td><td>X</td><td>Y</td><td>Z</td></tr>"
for i = 1 to 5
html "<tr align=right>"
for j = 1 to 4
if j = 1 then html "<td>";i;"</td>" else html "<td>";i;j;"</td>"
next j
html "</tr>"
next i
html "</table>"
Output:
| Row | X | Y | Z |
| 1 | 12 | 13 | 14 |
| 2 | 22 | 23 | 24 |
| 3 | 32 | 33 | 34 |
| 4 | 42 | 43 | 44 |
| 5 | 52 | 53 | 54 |
[edit] Scheme
(define table #(
#("" "X" "Y" "Z")
#(1 1 2 3)
#(2 4 5 6)
#(3 7 8 9)))
(display "<table>")
(do ((r 0 (+ r 1))) ((eq? r (vector-length table)))
(display "<tr>")
(do ((c 0 (+ c 1))) ((eq? c (vector-length (vector-ref table r))))
(if (eq? r 0)
(display "<th>"))
(if (> r 0)
(display "<td>"))
(display (vector-ref (vector-ref table r) c))
(if (eq? r 0)
(display "</th>"))
(if (> r 0)
(display "</td>")))
(display "</tr>"))
(display "</table>")
[edit] Seed7
$ include "seed7_05.s7i";
const proc: main is func
local
var integer: line is 0;
var integer: column is 0;
begin
writeln("<table style=\"text-align:center; border: 1px solid\">");
writeln("<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>");
for line range 1 to 3 do
write("<tr><th>" <& line <& "</th>");
for column range 1 to 3 do
write("<td>" <& rand(0, 9999) <& "</td>");
end for;
writeln("</tr>");
end for;
writeln("</table>")
end func;
Output:
<table style="text-align:center; border: 1px solid"> <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr> <tr><th>1</th><td>9682</td><td>2439</td><td>7698</td></tr> <tr><th>2</th><td>2958</td><td>4336</td><td>8340</td></tr> <tr><th>3</th><td>6245</td><td>6544</td><td>457</td></tr> </table>
Output viewed with a browser:
| X | Y | Z | |
|---|---|---|---|
| 1 | 9682 | 2439 | 7698 |
| 2 | 2958 | 4336 | 8340 |
| 3 | 6245 | 6544 | 457 |
[edit] Tcl
# Make ourselves a very simple templating lib; just two commands
proc TAG {name args} {
set body [lindex $args end]
set result "<$name"
foreach {t v} [lrange $args 0 end-1] {
append result " $t=\"" $v "\""
}
append result ">" [string trim [uplevel 1 [list subst $body]]] "</$name>"
}
proc FOREACH {var lst str} {
upvar 1 $var v
set result {}
set s [list subst $str]
foreach v $lst {append result [string trim [uplevel 1 $s]]}
return $result
}
# Build the data we're displaying
set titles {"" "X" "Y" "Z"}
set data {}
for {set x 0} {$x < 4} {incr x} {
# Inspired by the Go solution, but with extra arbitrary digits to show 4-char wide values
lappend data [list \
[expr {$x+1}] [expr {$x*3010}] [expr {$x*3+1298}] [expr {$x*2579+2182}]]
}
# Write the table to standard out
puts [TAG table border 1 {
[TAG tr bgcolor #f0f0f0 {
[FOREACH head $titles {
[TAG th {$head}]
}]
}]
[FOREACH row $data {
[TAG tr bgcolor #ffffff {
[FOREACH col $row {
[TAG td align right {$col}]
}]
}]
}]
}]
[edit] TUSCRIPT
$$ MODE TUSCRIPT
tablefile="table.html"
ERROR/STOP CREATE (tablefile,FDF-o,-std-)
ACCESS d: WRITE/ERASE/RECORDS/utf8 $tablefile s,tablecontent
tablecontent=*
WRITE d "<!DOCTYPE html system>"
WRITE d "<html><head><title>create html table</title></head>"
WRITE d "<body><table><thead align='right'>"
WRITE d "<tr><th> </th><th>x</th><th>y</th><th>z</th></tr>"
WRITE d "</thead>"
WRITE d "<tbody align='right'>"
LOOP n=1,5
x=RANDOM_NUMBERS (1,9999,1)
y=RANDOM_NUMBERS (1,9999,1)
z=RANDOM_NUMBERS (1,9999,1)
WRITE d "<tr><td>{n}</td><td>{x}</td><td>{y}</td><td>{z}</td></tr>"
ENDLOOP
WRITE d "</tbody></table></body></html>"
ENDACCESS d
BROWSE $tablefile
Output:
<!DOCTYPE html system> <html><head><title>create html table</title></head> <body><table><thead align='right'> <tr><th> </th><th>x</th><th>y</th><th>z</th></tr> </thead> <tbody align='right'> <tr><td>1</td><td>268</td><td>2409</td><td>8627</td></tr> <tr><td>2</td><td>2095</td><td>1455</td><td>269</td></tr> <tr><td>3</td><td>3763</td><td>9225</td><td>1957</td></tr> <tr><td>4</td><td>1304</td><td>9434</td><td>2208</td></tr> <tr><td>5</td><td>3547</td><td>4051</td><td>4859</td></tr> </tbody></table></body></html>
[edit] VBA
Public Sub BuildHTMLTable()
'simple HTML table, represented as a string matrix "cells"
Const nRows = 6
Const nCols = 4
Dim cells(1 To nRows, 1 To nCols) As String
Dim HTML As String 'the HTML table
Dim temp As String
Dim attr As String
' fill table
' first row with titles
cells(1, 1) = ""
cells(1, 2) = "X"
cells(1, 3) = "Y"
cells(1, 4) = "Z"
'next rows with index & random numbers
For i = 2 To nRows
cells(i, 1) = Format$(i - 1)
For j = 2 To nCols
cells(i, j) = Format$(Int(Rnd() * 10000))
Next j
Next i
'build the HTML
HTML = ""
For i = 1 To nRows
temp = ""
'first row as header row
If i = 1 Then attr = "th" Else attr = "td"
For j = 1 To nCols
temp = temp & HTMLWrap(cells(i, j), attr)
Next j
HTML = HTML & HTMLWrap(temp, "tr")
Next i
HTML = HTMLWrap(HTML, "table", "style=""text-align:center; border: 1px solid""")
Debug.Print HTML
End Sub
Public Function HTMLWrap(s As String, tag As String, ParamArray attributes()) As String
'returns string s wrapped in HTML tag with optional "attribute=value" strings
'ex.: HTMLWrap("Link text", "a", "href=""http://www.somesite.org""")
'returns: <a href="http://www.somesite.org">Link text</a>
Dim sOpenTag As String
Dim sClosingTag As String
sOpenTag = "<" & tag
For Each attr In attributes
sOpenTag = sOpenTag & " " & attr
Next
sOpenTag = sOpenTag & ">"
sClosingTag = "</" & tag & ">"
HTMLWrap = sOpenTag & s & sClosingTag
End Function
Subroutine BuildHTMLTable builds the HTML code as one big string. Sample output of call to BuildHMTLTable:
<table style="text-align:center; border: 1px solid"><tr><th></th><th>X</th><th>Y</th><th>Z</th></tr><tr><td>1</td><td>1906</td><td>6840</td><td>7474</td></tr><tr><td>2</td><td>6139</td><td>7821</td><td>1617</td></tr><tr><td>3</td><td>8077</td><td>2026</td><td>9567</td></tr><tr><td>4</td><td>658</td><td>615</td><td>7931</td></tr><tr><td>5</td><td>3796</td><td>4635</td><td>1195</td></tr></table>
which corresponds to:
| X | Y | Z | |
|---|---|---|---|
| 1 | 1906 | 6840 | 7474 |
| 2 | 6139 | 7821 | 1617 |
| 3 | 8077 | 2026 | 9567 |
| 4 | 658 | 615 | 7931 |
| 5 | 3796 | 4635 | 1195 |
- Programming Tasks
- Solutions by Programming Task
- HTML
- Ada
- AutoHotkey
- AWK
- BBC BASIC
- C
- C++
- C sharp
- CoffeeScript
- D
- Delphi
- Euphoria
- Go
- Groovy
- Icon
- Unicon
- Icon Programming Library
- J
- Java
- JavaScript
- Liberty BASIC
- Mathematica
- MATLAB
- Octave
- Modula-2
- NewLISP
- OCaml
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PicoLisp
- PL/I
- Protium
- Python
- Rascal
- Retro
- REXX
- Ruby
- REXML
- Run BASIC
- Scheme
- Seed7
- Tcl
- TUSCRIPT
- VBA
