如何用java制表
使用 String.format() 制表
String.format() 可以通过格式化字符串对齐文本。使用 %n 换行,%s 对齐字符串,%d 对齐数字,并指定宽度(如 %-10s 左对齐,%10s 右对齐)。
String header = String.format("%-10s %-10s %-10s", "Name", "Age", "City");
String row1 = String.format("%-10s %-10d %-10s", "Alice", 25, "New York");
String row2 = String.format("%-10s %-10d %-10s", "Bob", 30, "London");
System.out.println(header);
System.out.println(row1);
System.out.println(row2);
使用 System.out.printf() 制表
System.out.printf() 直接输出格式化内容,语法与 String.format() 类似。

System.out.printf("%-10s %-10s %-10s%n", "Name", "Age", "City");
System.out.printf("%-10s %-10d %-10s%n", "Alice", 25, "New York");
System.out.printf("%-10s %-10d %-10s%n", "Bob", 30, "London");
使用 StringBuilder 拼接表格
对于动态内容,StringBuilder 可以灵活拼接表格行和列,结合 \t 制表符或固定宽度对齐。

StringBuilder table = new StringBuilder();
table.append("Name\tAge\tCity\n");
table.append("Alice\t25\tNew York\n");
table.append("Bob\t30\tLondon\n");
System.out.println(table.toString());
使用第三方库(如 Apache Commons CSV)
若需生成复杂表格(如 CSV),可使用 Apache Commons CSV 等库。
// 添加依赖后示例
CSVPrinter printer = new CSVPrinter(new FileWriter("output.csv"), CSVFormat.DEFAULT);
printer.printRecord("Name", "Age", "City");
printer.printRecord("Alice", 25, "New York");
printer.printRecord("Bob", 30, "London");
printer.flush();
使用 HTML 生成表格
若需输出到网页,可直接生成 HTML 表格字符串。
String htmlTable = "<table border='1'><tr><th>Name</th><th>Age</th><th>City</th></tr>" +
"<tr><td>Alice</td><td>25</td><td>New York</td></tr>" +
"<tr><td>Bob</td><td>30</td><td>London</td></tr></table>";
System.out.println(htmlTable);
注意事项
- 对齐时需根据内容长度调整宽度,避免内容溢出。
- 动态数据建议使用循环遍历填充表格。
- 复杂需求可结合
List或二维数组存储数据后格式化输出。






