如何将df表格绘制到图片上并加上表格框线,使文字居中
时间: 2023-05-21 17:06:16 浏览: 98
您可以使用 Python 的 pandas 库中的 to_excel 函数将 df 表格导出为 Excel 文件,然后再使用 openpyxl 库中的 load_workbook() 函数加载该 Excel 文件,通过对应的工作表和单元格对象来对单元格的值、颜色、边框进行设置,最后保存为图片即可。下面是示例代码:
```python
import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Border, Side
from PIL import Image
# 创建示例数据
data = {'姓名': ['张三', '李四', '王五'],
'年龄': [18, 22, 20],
'性别': ['男', '女', '男']}
df = pd.DataFrame(data)
# 导出为 Excel 文件
writer = pd.ExcelWriter('table.xlsx', engine='openpyxl')
df.to_excel(writer, index=False, sheet_name='Sheet1')
writer.save()
# 加载 Excel 文件
book = load_workbook('table.xlsx')
sheet = book.active
# 设置单元格边框和对齐方式
border = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
for row in sheet.rows:
for cell in row:
cell.border = border
cell.alignment.horizontal = 'center'
cell.alignment.vertical = 'center'
# 保存为图片
img = Image.new('RGB', (sheet.max_column * 100, sheet.max_row * 30), color='white')
for row in sheet.rows:
for cell in row:
col_letter = cell.column_letter
img_draw = ImageDraw.Draw(img)
img_draw.text((ord(col_letter) * 100 - 90, cell.row * 30 - 20), str(cell.value), font=ImageFont.truetype('arial.ttf', 18), fill='black')
img_draw.rectangle([((ord(col_letter) - 1) * 100, (cell.row - 1) * 30), (ord(col_letter) * 100, cell.row * 30)], outline='black')
img.save('table.jpg')
```
阅读全文