Java Generating Formatted Report in Text file format
Solution 1
Just as an alternative, here is 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
Solution 2
Apache Velocity is a good tool for text formating or templating. It works with plain text, HTML, JSP, XML, SQL scripts, etc. Here is a nice helloWorld tutorial about it.
The basic steps are:
- Write your text template.
- Initialize the Velocity Engine.
- Insert the context that you need.
- And render it.
Others like Latex are more complex but really more powerful. Take a look to JasperReports if you need just reporting formats.
coldholic
Updated on June 27, 2022Comments
-
coldholic almost 2 years
Halo,
I have been looking for a way to generate a nicely formatted report in text file using java.
For example, I might 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 have tried writing my own program, but I just feel that its a mess!!! So I am wondering if there are any existing library that I can use or is there a good way to implement it??
By the way, I have look around and found a library that are similar to what I want https://github.com/iNamik/Java-Text-Table-Formatter
Just wondering if there are other options. Thanks for helping!!
====================================================================
So I have made a sample code that I probably will use to clean up 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());
Output:
A Monthly Report A Report Name A A Category Quantity Price A -------------- -------------- -------------- B Paper 100 $200
I am thinking how can I make the "Report Name" at the center and "Page No:" at the right without hard coding the int argument of the formatter (i.e. %50s, without 50, is it possible)