如何将plt.show()生成的图片缩小保存进已有excel的某一列中
时间: 2023-03-29 11:01:26 浏览: 182
您可以使用Pillow库中的Image模块将图片缩小后再保存到Excel中。具体步骤如下:
1. 使用plt.savefig()保存图片到本地。
2. 使用Image模块打开图片,调整大小并保存。
3. 使用openpyxl库打开Excel文件,将图片插入到指定单元格中。
示例代码如下:
```python
import matplotlib.pyplot as plt
from PIL import Image
from openpyxl import load_workbook
# 保存图片
plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig('figure.png')
# 调整图片大小
img = Image.open('figure.png')
img = img.resize((200, 150))
img.save('figure_small.png')
# 将图片插入到Excel中
wb = load_workbook('example.xlsx')
ws = wb.active
img = Image.open('figure_small.png')
img_cell = ws.cell(row=1, column=1)
img_cell._style = 'align: center' # 图片居中显示
img_cell.value = ' ' # 设置单元格值为空,否则图片会被覆盖
img_cell.anchor = 'D2' # 设置图片位置
img_cell.width = 200 # 设置图片宽度
img_cell.height = 150 # 设置图片高度
img_cell._image = openpyxl.drawing.image.Image('figure_small.png')
wb.save('example.xlsx')
```
注意:需要安装Pillow和openpyxl库。
阅读全文
相关推荐











