美文网首页
python将表格展示的数据生成图片

python将表格展示的数据生成图片

作者: 洛奇lodge | 来源:发表于2020-07-15 22:51 被阅读0次
概述

最近有一个需求,在界面对表格进行自动截图,然后将图片存起来

方案

第一种: selenium +chromedirver + pillow
使用自动化工具,网页截图, 通过元素定位到具体位置,pillow进行裁剪得出最理想结果,此方案还是存在很大误差,因为表格数据数量非固定的,计算误差很大,难以精准

第二种: prettytable + pillow
通过prettytable将数据生成简单表格布局,通过pillow 生成图片,这个方案简单容易,但是表格样式过于丑陋,暂不考虑

第三种: html-table + imgkit
通过html-table将数据生成带样式的html文件,然后使用imgkit 转换成图片,该方案是目前最理想的

实施过程

1、环境安装

  • python库安装
pip insatll  html-table==1.0
pip insatll imgkit==1.0.2

2、demo演示

import imgkit
from HTMLTable import  HTMLTable

# 标题
table = HTMLTable(caption='果园收成表')
# 表头行
table.append_header_rows((
    ('名称', '产量 (吨)','增长量 (吨)','增长率 (%)'),
))

# 数据行
table.append_data_rows((
    ('荔枝', 11, 1, 10),
    ('芒果', 9, -1, -10),
    ('香蕉', 6, 1, 20),
))
# 标题样式
table.caption.set_style({
    'font-size': '15px',
})
# 表格样式,即<table>标签样式
table.set_style({
    'border-collapse': 'collapse',
    'word-break': 'keep-all',
    'white-space': 'nowrap',
    'font-size': '14px',
})
# 统一设置所有单元格样式,<td>或<th>
table.set_cell_style({
    'width': "250px",
    'border-color': '#000',
    'border-width': '1px',
    'border-style': 'solid',
    'padding': '5px',
})
# 表头样式
table.set_header_row_style({
    'color': '#fff',
    'background-color': '#48a6fb',
    'font-size': '18px',
})

# 覆盖表头单元格字体样式
table.set_header_cell_style({
    'padding': '15px',
})
# 调小次表头字体大小
table[1].set_cell_style({
    'padding': '8px',
    'font-size': '15px',
})
# 遍历数据行,如果增长量为负,标红背景颜色
for row in table.iter_data_rows():
    if row[2].value < 0:
        row.set_style({
            'background-color': '#ffdddd',
        })
body = table.to_html()
# html的charset='UTF-8'必须加上,否则中午会乱码
html = "<!DOCTYPE html><html><head><meta charset='UTF-8'></head><body>{0}</body></html>".format(body)

# 生成图片
imgkit.from_string(html, 'out.jpg')

imgkit官方文档:https://github.com/jarrekk/imgkit

相关文章

网友评论

      本文标题:python将表格展示的数据生成图片

      本文链接:https://www.haomeiwen.com/subject/jckshktx.html