5个案例让Python输出漂亮的表格( 二 )


 
B、按列添加数据 table.add_column看下面的示例:
 #!/usr/bin/python
#**coding:utf-8**
import sys
from prettytable import PrettyTable
reload(sys)
sys.setdefaultencoding('utf8')
table = PrettyTable
table.add_column('项目', ['编号','云编号','名称','IP地址'])
table.add_column('值', ['1','server01','服务器01','172.16.0.1'])
print(table)
运行结果如下:
 +-------+--------+------------+
| index | 项目 | 值 |
+-------+--------+------------+
| 1 | 编号 | 1 |
| 2 | 云编号 | server01 |
| 3 | 名称 | 服务器01 |
| 4 | IP地址 | 172.16.0.1 |
+-------+--------+------------+
以上示例中 , 我们通过add_column来按列添加数据 , 按列添加数据不需要在实例化表格的时候制定表头 , 它的表头是在添加列的时候指定的 。
table.add_column('项目', ['编号','云编号','名称','IP地址'])这一行代码为例 , 项目指定了这个列的表头名为"项目" , ['编号','云编号','名称','IP地址']为列的值 , 同样为列表 。
 
C、从csv文件添加数据PrettyTable不仅提供了手动按行按列添加数据 , 也支持直接从csv文件中读取数据 。
 #!/usr/bin/python
#**coding:utf-8**
import sys
from prettytable import PrettyTable
from prettytable import from_csv
reload(sys)
sys.setdefaultencoding('utf8')
table = PrettyTable
fp = open("res.csv", "r")
table = from_csv(fp)
print(table)
fp.close
如果要读取cvs文件数据 , 必须要先导入from_csv , 否则无法运行 。上面的示例运行结果如下:
 +------+----------+----------+------------+
| 编号 | 云编号 | 名称 | IP地址 |
+------+----------+----------+------------+
| 1 | server01 | 服务器01 | 172.16.0.1 |
| 2 | server02 | 服务器02 | 172.16.0.2 |
| 3 | server03 | 服务器03 | 172.16.0.3 |
| 4 | server04 | 服务器04 | 172.16.0.4 |
| 5 | server05 | 服务器05 | 172.16.0.5 |
| 6 | server06 | 服务器06 | 172.16.0.6 |
| 7 | server07 | 服务器07 | 172.16.0.7 |
| 8 | server08 | 服务器08 | 172.16.0.8 |
| 9 | server09 | 服务器09 | 172.16.0.9 |
+------+----------+----------+------------+

csv文件不能通过xls直接重命名得到 , 会报错 。如果是xls文件 , 请用另存为csv获得csv文件
 
D、从sql查询值添加从数据库查询出来的数据可以直接导入到表格打印 , 下面的例子使用了sqlite3,如果使用的是MySQL也是一样的 , 只要能查询到数据就能导入到表格中
 #!/usr/bin/python
#**coding:utf-8**
import sys
from prettytable import PrettyTable
from prettytable import from_db_cursor
import sqlite3
reload(sys)
sys.setdefaultencoding('utf8')
conn = sqlite3.connect("/tmp/aliyun.db")
cur = conn.cursor
cur.execute("SELECT * FROM res")
table = from_db_cursor(cur)
print(table)
运行结果如下:
 +------+----------+----------+------------+
| 编号 | 云编号 | 名称 | IP地址 |
+------+----------+----------+------------+
| 1 | server01 | 服务器01 | 172.16.0.1 |
| 2 | server02 | 服务器02 | 172.16.0.2 |
| 3 | server03 | 服务器03 | 172.16.0.3 |
| 4 | server04 | 服务器04 | 172.16.0.4 |
| 5 | server05 | 服务器05 | 172.16.0.5 |
| 6 | server06 | 服务器06 | 172.16.0.6 |
| 7 | server07 | 服务器07 | 172.16.0.7 |
| 8 | server08 | 服务器08 | 172.16.0.8 |
| 9 | server09 | 服务器09 | 172.16.0.9 |
+------+----------+----------+------------+
 
E、从html导入数据支持从html的表格中导入 , 请看下面这个例子:
 #!/usr/bin/python
#**coding:utf-8**
import sys
from prettytable import PrettyTable
from prettytable import from_html
reload(sys)
sys.setdefaultencoding('utf8')
html_string='''<table>
<tr>
<th>编号</th>
<th>云编号</th>
<th>名称</th>
<th>IP地址</th>
</tr>
<tr>
<td>1</td>
<td>server01</td>


推荐阅读