You can try Text Table Formatter. It's not a perfect library: it doesn't have JavaDocs, it doesn't have a user guide, the source code contains typos (e.g. see the ShownBorders
class that contains a HEADER_AND_FIRST_COLLUMN
constant). Even this project page that contains examples of usages has at least one typo (HorizontalAlign.right
instead of HorizontalAlign.RIGHT
). However, it's in the Maven Central repository (unlike iNamik's Text Table Formatter), pretty flexible, easy to use, and it works. Here's the fixed "advanced" example provided by the library's creators
public class Advanced {
public static void main(final String[] args) {
CellStyle numberStyle = new CellStyle(HorizontalAlign.RIGHT);
Table t = new Table(3, BorderStyle.DESIGN_FORMAL,
ShownBorders.SURROUND_HEADER_FOOTER_AND_COLUMNS);
t.setColumnWidth(0, 8, 14);
t.setColumnWidth(1, 7, 16);
t.setColumnWidth(2, 9, 16);
t.addCell("Region");
t.addCell("Orders", numberStyle);
t.addCell("Sales", numberStyle);
t.addCell("North");
t.addCell("6,345", numberStyle);
t.addCell("$87.230", numberStyle);
t.addCell("Center");
t.addCell("837", numberStyle);
t.addCell("$12.855", numberStyle);
t.addCell("South");
t.addCell("5,344", numberStyle);
t.addCell("$72.561", numberStyle);
t.addCell("Total", numberStyle, 2);
t.addCell("$172.646", numberStyle);
System.out.println(t.render());
}
}
Output:
==========================
Region Orders Sales
-------- ------- ---------
North 6,345 $87.230
Center 837 $12.855
South 5,344 $72.561
-------- ------- ---------
Total $172.646
==========================
Another option (I personally like it more) is ASCII Table. Unlike the previous library, it has a good user guide, JavaDocs, and multiple versions in Maven Central (which implies it was maintained, at least for a while, the last one is of May 2017). Here's an example of what you can do with it (I'll omit the class and main method declarations)
AsciiTable table = new AsciiTable();
table.getContext().setGrid(A8_Grids.lineDobuleTripple());
table.addHeavyRule();
table.addRow(null, null, "Countries");
table.addHeavyRule();
table.addRow("Country", "Capital", "Population");
table.addRule();
table.addRow("United States", "Washington", "333,287,557");
table.addRow("United Kingdom", "London", "68,138,484");
table.addRow("Australia", "Canberra", "26,540,400");
table.addHeavyRule();
System.out.println(table.render());
Output:
≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
Countries
≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
Country Capital Population
────────────────────────────────────────────────────────────────────────────────
United States Washington 333,287,557
United Kingdom London 68,138,484
Australia Canberra 26,540,400
≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡