Java Create a formatted report in text format

halo,

I was looking for a way to create a well formatted report in a text file using java.

For example, I may need to print a report in the following format

  A monthly report
 A Report Name Page No: 1
 A Date: YYYY-MM-DD              
 A
 A Category Quantity Price
 A ----------------- ----------------- --------------- -----
 B Pen 100 $ 100
 B Paper 200 $ 400
 A
 A ================== ====================
 B Total $ 500
 A ================== ====================

I tried writing my own program, but I just feel like its a mess! So I wonder if there is any existing library that I can use, or is there a good way to implement it?

By the way, I looked around and found a library similar to what I want https://github.com/iNamik/Java-Text-Table-Formatter

Just wondering if there are other options. Thanks for the help!

==================================================== ===================

So, I made a code example that I will probably use to clear my code

  StringBuilder sb = new StringBuilder(); sb.append(String.format("%s %50s%n", "A", "Monthly Report")); sb.append(String.format("%s %48s%n", "A", "Report Name")); sb.append(String.format("%s %n", "A")); sb.append(String.format("%s %-20s %-20s %-20s%n", "A", "Category", "Quantity", "Price")); sb.append(String.format("%s %-20s %-20s %-20s%n", "A", "--------------", "--------------", "--------------")); sb.append(String.format("%s %-20s %-20s %-20s%n", "B", "Paper", 100, "$200")); System.out.println(sb.toString()); 

Code> Output:

 A monthly report
 A report name
 AA Category Quantity Price               
 A -------------- -------------- --------------      
 B Paper 100 $ 200                


I think, how can I do “Report Name” in the center and “Page No.:” on the right without hard-coding the formatting int argument (ie% 50s, without 50, is this possible)

+4
source share
3 answers

As an alternative, here is a JDK based solution

 public static void main(String[] args) throws Exception { printRow("A", "Category", "Quantity", "Price"); printRow("A", "--------------", "--------------", "--------------"); printRow("B", "Paper", 100, 200); } private static void printRow(String c0, String c1, Object c2, Object c3 ) { System.out.printf("%s %-20s %-20s %-20s%n", c0, c1, String.valueOf(c2), c3 instanceof Integer ? "$" + c3 : c3); } 

Output

 A Category Quantity Price A -------------- -------------- -------------- B Paper 100 $200 
+4
source

Apache Velocity is a good tool for formatting text or templates. It works with text scripts, HTML, JSP, XML, SQL scripts, etc. Here is a good one about that.

The main steps:

  • Write your text template.
  • Initialize the speed engine.
  • Paste the context you need.
  • And draw it.

Others, such as Latex , are more complex, but more powerful. Check out JasperReports if you only need report formats.

+2
source

Try the iText java library that I used to create bills for my application.

0
source

All Articles