Skip to: Site menu | Main content

Groovy 

      Download | Documentation | Developers | Community

An agile dynamic language for the Java Platform

Formatting simple tabular text data Add comment to Wiki View in Wiki Edit Wiki page Printable Version

Formatting simple tabular text data

This class has been posted first time on the Groovy-User Mailing List by Raffaele Castagno in this format:

class TableTemplateFactory
{
   def columns = [];     // contains columns names and theyr length
   def header1 = '';     // contains columns names
   def header2 = '';     // contains underscores
   def body    = '';     // the rows of the table
   def footer  = '';     // actually unused: can contain footer notes, totals, etc.

   def addColumn(name, size)
   {
     columns << [name:name, size:size];
   }

   def getTemplate()
   {
     header1 = "\n";
     columns.each{ header1 += ' <%print "'+it.name+'".center('+it.size+')%> ' };
     header2 = "\n";
     columns.each{ header2 += ' <%print "_"*'+it.size+' %> ' };
     body = '\n<% rows.each {%>';
     // If a value is longer than given column name, it will be trunked
     columns.each{body += ' ${it.'+it.name+'.toString().padRight('+it.size+').substring(0,'+it.size+')} '};
     body += '\n<% } %>';
     return header1 + header2 + body + footer;
   }   }

 and later "groovyfied" by Gavin Grover:

class TableTemplateFactory{
  def columns = []
  def addColumn(name, size) { columns << [name:name, size:size]; this }
  def getTemplate() { """
${columns.collect{ " <%print \"$it.name\".center($it.size)%> " }.join()}
${columns.collect{ " <%print \"_\"*$it.size %> " }.join()}
<% rows.each {%>${columns.collect{ " \${it.${it.name}.toString().padRight($it.size).substring(0,$it.size)} " }.join()}
<% } %>"""
    }
}

 First version is here only as an example of the "groovify process". Of course, the Gavin's version is better.

This class emulate the output of most RDBMS consoles (ie. Oracle SQL*, MySql).

Here's an usage example (again, grooved up by Gavin):

import groovy.text.Template; import groovy.text.SimpleTemplateEngine
def ttf = new TableTemplateFactory().addColumn("name", 15).addColumn("age", 4)
def names = [] << [name:"Raffaele", age:"23"] << [name:"Griorgio", age:"30"]
def binding = ['rows': names]
println new SimpleTemplateEngine().createTemplate(ttf.template).make(binding).toString()

This is the output:

      name        age
 _______________  ____
 Raffaele         23  
 Griorgio         30  

Actually is really limited: column width must be declared, and strings are truncated to that given size.

Wish-list: 

  • Automatic column width based on maximum string length
  • Multiline records
  • Multiline fields
  • More formatting options (alignment, case, etc)
  • Management of footer fields (totals, formulae, etc)
  • Automatic line-wrap based on screen size