col*_*lic 5 java format text report
光环,
我一直在寻找一种使用java在文本文件中生成格式良好的报表的方法.
例如,我可能需要以下列格式打印报告
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 ================= ====================
我试过写自己的程序,但我觉得它很乱!所以我想知道是否有任何现有的库我可以使用或有一个很好的方法来实现它?
顺便说一句,我环顾四周,发现了一个类似于我想要的库 https://github.com/iNamik/Java-Text-Table-Formatter
只是想知道是否还有其他选择.谢谢你的帮助!!
================================================== ==================
所以我制作了一个示例代码,我可能会用它来清理我的代码
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());
Run Code Online (Sandbox Code Playgroud)
输出:
A Monthly Report A Report Name A A Category Quantity Price A -------------- -------------- -------------- B Paper 100 $200
我在想我怎样才能使"报告名称"在中心和"页码:"在合适的不硬编码格式的int参数(即50年代%,无50,有没有可能)
作为替代方案,这里是基于 JDK 的解决方案
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);
}
Run Code Online (Sandbox Code Playgroud)
输出
A Category Quantity Price
A -------------- -------------- --------------
B Paper 100 $200
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13731 次 |
| 最近记录: |