带有多个标题/标题的Python PrettyTable

时间:2018-07-18 18:47:52

标签: python prettytable

我能够创建带有标题和表格字段的python PrettyTable。但是,我想在一个表中创建多个节,即具有多个标题(或html rowspan / colspan合并单元格以创建节)。 有任何指针吗?

当前,我可以使用以下方式创建表格:

table_fields = ['No','Name', 'Age']
from prettytable import PrettyTable
pt = PrettyTable(table_fields)
pt.padding_width = 1
pt.title = 'Customer Info'
pt.add_row(['1','abc','26'])
pt.add_row(['2','xyz','52'])

输出:

+------------------------------+
|    Customer Info             |
+------------------------------+ 
| No | Name      |    Age      |
+------------------------------+
| 1  |  abc      |   26        |
| 2  |  xyz      |   52        |
+------------------------------+

所需的输出:

+------------------------------+
|    Customer Info             |
+------------------------------+ 
| No | Name      |    Age      |
+------------------------------+
|  DEPARTMENT 1                |
+------------------------------+
| 1  |  abc      |   26        |
| 2  |  xyz      |   52        |
+------------------------------+
|  DEPARTMENT 2                |
+------------------------------+
| 1  |  pqr      |   44        |
| 2  |  def      |   31        |
+------------------------------+

寻找一种在表中添加部门1和部门2行的方法。

1 个答案:

答案 0 :(得分:0)

在这里,我已经尽可能接近期望的输出了(每次将新部门的人员添加到表中时,都使用一行作为部门号): 注意:我无法找到一种方法来更改单元格的列跨度,因此我必须添加空格以填充期望的单元格数,否则无法添加行。

+---------------------------+
|       Customer Info       |
+--------------+------+-----+
|      No      | Name | Age |
+--------------+------+-----+
| DEPARTMENT 1 |      |     |
|      1       | abc  |  41 |
|      2       | def  |  29 |
| DEPARTMENT 2 |      |     |
|      1       | pqr  |  21 |
|      2       | xyz  |  37 |
+--------------+------+-----+

使用以下代码:

from prettytable import PrettyTable

departments = {
    "1": {
        "abc": {
            "age": 41
        },
        "def": {
            "age": 29
        }
    },
    "2": {
        "pqr": {
            "age": 21
        },
        "xyz": {
            "age": 37
        }
    }
}

table_fields = ['No', 'Name', 'Age']
pt = PrettyTable(table_fields)
pt.padding_width = 1
pt.title = 'Customer Info'
person_no = 1
for department, people in departments.items():
    pt.add_row(["DEPARTMENT {}".format(department), "", ""])
    for name, person in people.items():
        pt.add_row([person_no, name, person["age"]])
        person_no += 1
    person_no = 1
print(pt)

我希望这足以满足您的需求,如果您或其他任何人知道如何为一个单元格指定列跨度,我想知道!