有没有用于绘制 ASCII 表格的 Java 库?

发布于 2024-10-31 12:35:05 字数 379 浏览 1 评论 0原文

我需要将数据作为表格输出到控制台。我想知道也许有一些 java 库可以处理 ASCII 艺术中的绘图表格、对齐单元格内的值等?

 ╔══════╤═══════════╤════════╗
 ║  ID  │ Name      │  Age   ║ 
 ╠══════╪═══════════╪════════╣
 ║  1   │ John      │   24   ║ 
 ╟──────┼───────────┼────────╢
 ║  2   │ Jeff      │   19   ║ 
 ╟──────┼───────────┼────────╢
 ║  3   │ Joel      │   42   ║ 
 ╚══════╧═══════════╧════════╝

I need to output data into a console as a table. I was wondering maybe there are some java libraries that would take care of drawing tables in ASCII art, aligning values inside cells, etc?

 ╔══════╤═══════════╤════════╗
 ║  ID  │ Name      │  Age   ║ 
 ╠══════╪═══════════╪════════╣
 ║  1   │ John      │   24   ║ 
 ╟──────┼───────────┼────────╢
 ║  2   │ Jeff      │   19   ║ 
 ╟──────┼───────────┼────────╢
 ║  3   │ Joel      │   42   ║ 
 ╚══════╧═══════════╧════════╝

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

↙温凉少女 2024-11-07 12:35:05

这对我来说效果很好:http://code.google.com/p/java-ascii-table/

String [] header = {
      "User Name", 
      "Salary", "Designation",
      "Address", "Lucky#"
};

String[][] data = {
      { "Ram", "2000", "Manager", "#99, Silk board", "1111"  },
      { "Sri", "12000", "Developer", "BTM Layout", "22222" },
      { "Prasad", "42000", "Lead", "#66, Viaya Bank Layout", "333333" },
      { "Anu", "132000", "QA", "#22, Vizag", "4444444" },
      { "Sai", "62000", "Developer", "#3-3, Kakinada"  },
      { "Venkat", "2000", "Manager"   },
      { "Raj", "62000"},
      { "BTC"},
};

呈现以下内容:

+-----------+--------+-------------+------------------------+---------+
| User Name | Salary | Designation |         Address        |  Lucky# |
+-----------+--------+-------------+------------------------+---------+
|       Ram |   2000 |     Manager |        #99, Silk board |    1111 |
|       Sri |  12000 |   Developer |             BTM Layout |   22222 |
|    Prasad |  42000 |        Lead | #66, Viaya Bank Layout |  333333 |
|       Anu | 132000 |          QA |             #22, Vizag | 4444444 |
|       Sai |  62000 |   Developer |         #3-3, Kakinada |         |
|    Venkat |   2000 |     Manager |                        |         |
|       Raj |  62000 |             |                        |         |
|       BTC |        |             |                        |         |
+-----------+--------+-------------+------------------------+---------+

This worked pretty well for me: http://code.google.com/p/java-ascii-table/

String [] header = {
      "User Name", 
      "Salary", "Designation",
      "Address", "Lucky#"
};

String[][] data = {
      { "Ram", "2000", "Manager", "#99, Silk board", "1111"  },
      { "Sri", "12000", "Developer", "BTM Layout", "22222" },
      { "Prasad", "42000", "Lead", "#66, Viaya Bank Layout", "333333" },
      { "Anu", "132000", "QA", "#22, Vizag", "4444444" },
      { "Sai", "62000", "Developer", "#3-3, Kakinada"  },
      { "Venkat", "2000", "Manager"   },
      { "Raj", "62000"},
      { "BTC"},
};

Which renders the following:

+-----------+--------+-------------+------------------------+---------+
| User Name | Salary | Designation |         Address        |  Lucky# |
+-----------+--------+-------------+------------------------+---------+
|       Ram |   2000 |     Manager |        #99, Silk board |    1111 |
|       Sri |  12000 |   Developer |             BTM Layout |   22222 |
|    Prasad |  42000 |        Lead | #66, Viaya Bank Layout |  333333 |
|       Anu | 132000 |          QA |             #22, Vizag | 4444444 |
|       Sai |  62000 |   Developer |         #3-3, Kakinada |         |
|    Venkat |   2000 |     Manager |                        |         |
|       Raj |  62000 |             |                        |         |
|       BTC |        |             |                        |         |
+-----------+--------+-------------+------------------------+---------+
囚我心虐我身 2024-11-07 12:35:05

我喜欢你的桌子并写道:
https://github.com/klaus31/ascii-art-table

I like your table and wrote that:
https://github.com/klaus31/ascii-art-table

断念 2024-11-07 12:35:05

这里还有一个方便的库: https://github.com/JakeWharton/flip-tables

作为文档说:

String[] headers = { "Test", "Header" };
String[][] data = {
    { "Foo", "Bar" },
    { "Kit", "Kat" },
};
System.out.println(FlipTable.of(headers, data));

应该有以下输出:

╔══════╤════════╗
║ Test │ Header ║
╠══════╪════════╣    
║ Foo  │ Bar    ║
╟──────┼────────╢
║ Kit  │ Kat    ║
╚══════╧════════╝

Here is also a handy library: https://github.com/JakeWharton/flip-tables

As the doc said:

String[] headers = { "Test", "Header" };
String[][] data = {
    { "Foo", "Bar" },
    { "Kit", "Kat" },
};
System.out.println(FlipTable.of(headers, data));

should have the following output:

╔══════╤════════╗
║ Test │ Header ║
╠══════╪════════╣    
║ Foo  │ Bar    ║
╟──────┼────────╢
║ Kit  │ Kat    ║
╚══════╧════════╝
怀里藏娇 2024-11-07 12:35:05

您可以尝试文本表格式化程序 。它不是一个完美的库:它没有 JavaDocs,没有用户指南,源代码包含拼写错误(例如,请参阅包含 HEADER_AND_FIRST_COLLUMN 的 ShownBorders 类) > 常数)。甚至此项目页面也包含示例的用法至少有一个拼写错误(Horizo​​ntalAlign.right 而不是 Horizo​​ntalAlign.RIGHT)。但是,它位于 Maven 中央存储库中(与 iNamik 的文本表格式化程序不同),非常灵活,易于使用,而且有效。这是库创建者提供的固定“高级”示例

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());
  }

}

输出:

==========================
Region    Orders     Sales
-------- ------- ---------
North      6,345   $87.230
Center       837   $12.855
South      5,344   $72.561
-------- ------- ---------
           Total  $172.646
==========================

另一个选项(我个人更喜欢它)是 ASCII 表。与之前的库不同,它有一个很好的用户指南JavaDocs,以及 Maven Central 中的多个版本(这意味着它被维护,至少有一段时间,最后一次是2017年5月)。这是一个可以用它做什么的示例(我将省略类和主方法声明)

        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());

输出:

≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
 Countries                                                                      
≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
 Country                    Capital                   Population                
────────────────────────────────────────────────────────────────────────────────
 United States              Washington                333,287,557               
 United Kingdom             London                    68,138,484                
 Australia                  Canberra                  26,540,400                
≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡

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                
≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
花开雨落又逢春i 2024-11-07 12:35:05

如果您已经有一个具有所需列宽的格式化二维字符串数组,那么您可以自己绘制一个简单的表格,无需任何库,如下所示:

+------+---------+-------+
|  ID  |  Name   |  Age  |
+------+---------+-------+
|   1  |  John   |   24  |
+------+---------+-------+
|   2  |  Jeff   |   19  |
+------+---------+-------+
|   3  |  Joel   |   42  |
+------+---------+-------+

尝试一下在线!

public static String drawTable(String[][] table) {
    String borderRow = Arrays.stream(table[0])
            // border row between rows
            .map(str -> "-".repeat(str.length()))
            .collect(Collectors.joining("+", "+", "+\n"));
    return Arrays.stream(table)
            // table row with borders between cells
            .map(row -> Arrays.stream(row)
                    .collect(Collectors.joining("|", "|", "|\n")))
            .collect(Collectors.joining(borderRow, borderRow, borderRow));
}
public static void main(String[] args) {
    String[][] table = {
            {"  ID  ", "  Name   ", "  Age  "},
            {"   1  ", "  John   ", "   24  "},
            {"   2  ", "  Jeff   ", "   19  "},
            {"   3  ", "  Joel   ", "   42  "}};

    System.out.println(drawTable(table));
}

另请参阅:

如何用Java绘制楼梯?

格式化二维数字数组

If you already have a formatted 2d array of strings with the desired column widths, then you can draw a simple table yourself without any libraries, something like this:

+------+---------+-------+
|  ID  |  Name   |  Age  |
+------+---------+-------+
|   1  |  John   |   24  |
+------+---------+-------+
|   2  |  Jeff   |   19  |
+------+---------+-------+
|   3  |  Joel   |   42  |
+------+---------+-------+

Try it online!

public static String drawTable(String[][] table) {
    String borderRow = Arrays.stream(table[0])
            // border row between rows
            .map(str -> "-".repeat(str.length()))
            .collect(Collectors.joining("+", "+", "+\n"));
    return Arrays.stream(table)
            // table row with borders between cells
            .map(row -> Arrays.stream(row)
                    .collect(Collectors.joining("|", "|", "|\n")))
            .collect(Collectors.joining(borderRow, borderRow, borderRow));
}
public static void main(String[] args) {
    String[][] table = {
            {"  ID  ", "  Name   ", "  Age  "},
            {"   1  ", "  John   ", "   24  "},
            {"   2  ", "  Jeff   ", "   19  "},
            {"   3  ", "  Joel   ", "   42  "}};

    System.out.println(drawTable(table));
}

See also:

How to draw a staircase with Java?

Formatting 2d array of numbers

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文