Plotly图表转PNG插入PPT时出现'seek'属性错误的求助
Plotly图表转PNG插入PPT时出现'seek'属性错误的求助
嗨,我懂你碰到的这个问题!之前我也踩过类似的坑,咱们来快速解决它~
问题原因
python-pptx的insert_picture()方法并不接受直接的bytes对象作为参数,它需要的是具备文件操作能力的类文件对象(也就是有seek方法的对象),而单纯的bytes数据是没有这个方法的,所以才会抛出'bytes' object has no attribute 'seek'的错误。
解决方案
我们只需要把生成的bytes对象包装成BytesIO对象就行,BytesIO会把字节数据模拟成文件流,完美满足insert_picture()的要求。具体步骤如下:
- 首先导入
BytesIO类:
from io import BytesIO
- 把Plotly生成的图片bytes转换成类文件对象:
img_file = BytesIO(img_bytes)
- 最后用这个类文件对象去插入图片:
placeholder.insert_picture(img_file)
修改后的完整代码
import plotly.express as px import plotly.io as pio from pptx import Presentation from io import BytesIO # 新增导入 wide_df = px.data.medals_wide() fig = px.bar(wide_df, x="nation", y=["gold", "silver", "bronze"], title="Wide-Form Input, relabelled", labels={"value": "count", "variable": "medal"}) # 转换为bytes对象 img_bytes = pio.to_image(fig, format='png') # 包装成类文件对象 img_file = BytesIO(img_bytes) ppt = Presentation("template.pptx") slide = ppt.slides[3] placeholder = slide.placeholders[13] # 使用包装后的对象插入图片 placeholder.insert_picture(img_file) # 别忘了保存PPT哦! ppt.save("output.pptx")
这样修改之后,应该就能顺利把Plotly图表插入到PPT幻灯片里啦~
备注:内容来源于stack exchange,提问作者Tonino Fernandez




