You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用xlwings 0.11.8插入Matplotlib图表到Excel无显示的问题排查

问题:xlwings 0.11.8插入Matplotlib图表至Excel无显示

背景信息

项目受限于库版本,基于以下样本数据:

Months   Number of records(mili)
Dec_18   46
Jan_19   70

通过Matplotlib生成柱状图,代码如下:

o = data.set_index('Months')
ax = o.plot.bar(figsize=(12, 6),width=0.8)
plt.xticks(rotation=360, horizontalalignment="center")

for p in ax.patches:
    ax.annotate(format(p.get_height()), (p.get_x() + p.get_width() / 2.,p.get_y() + p.get_height()/2), ha = 'center', va = 'center', color = font_color,fontsize=20)

ax.legend(loc = 'lower center', bbox_to_anchor=(0.5,-0.2))

随后使用xlwings 0.11.8将图表插入Excel,代码如下:

workbook = xw.Book("PlanA.xlsx")
sht = workbook.sheets[0]
sht.name = "Python Charts"
fig = ax.get_figure()
sht.pictures.add(fig, name = 'abc', update=True,
                left = sht.range('A6').left, top = sht.range('A6').top,
                height = 300, width = 500)

代码无报错,但生成的Excel文件中未显示图表,需解决该问题并提供适配xlwings 0.11.8的修改建议。

问题排查与修改建议

  • 确保Matplotlib图表完成渲染
    xlwings 0.11.8对未完全渲染的Matplotlib figure支持有限,需在插入前强制渲染图表:

    fig = ax.get_figure()
    fig.canvas.draw()  # 添加该行,确保图表渲染完成
    
  • 修正update参数的使用
    0.11.8版本中,update=True仅用于更新已存在的同名图片。首次插入时应设置为update=False,否则会因找不到目标图片而跳过插入:

    sht.pictures.add(fig, name = 'abc', update=False,
                    left = sht.range('A6').left, top = sht.range('A6').top,
                    height = 300, width = 500)
    
  • 显式保存工作簿
    操作完成后需手动保存工作簿,避免修改未写入文件:

    workbook.save()
    workbook.close()  # 可选,确保资源释放
    
  • 验证文件路径与工作表目标

    • 确认PlanA.xlsx的路径正确,若使用相对路径需保证脚本运行目录与文件目录一致;
    • 若原Excel存在多个工作表,workbook.sheets[0]指向第一个工作表,可通过sht.name确认是否为目标表。

完整适配后的代码示例

# Matplotlib图表生成部分
o = data.set_index('Months')
ax = o.plot.bar(figsize=(12, 6),width=0.8)
plt.xticks(rotation=360, horizontalalignment="center")

for p in ax.patches:
    ax.annotate(format(p.get_height()), (p.get_x() + p.get_width() / 2.,p.get_y() + p.get_height()/2), ha = 'center', va = 'center', color = font_color,fontsize=20)

ax.legend(loc = 'lower center', bbox_to_anchor=(0.5,-0.2))

# xlwings插入部分
import xlwings as xw

workbook = xw.Book("PlanA.xlsx")
sht = workbook.sheets[0]
sht.name = "Python Charts"
fig = ax.get_figure()
fig.canvas.draw()  # 强制渲染图表

sht.pictures.add(fig, name = 'abc', update=False,
                left = sht.range('A6').left, top = sht.range('A6').top,
                height = 300, width = 500)

workbook.save()
workbook.close()

内容的提问来源于stack exchange,提问作者sha25

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 11:25:30