Python win32 Excel将图表粘贴为位图(PasteSpecial)?

2024-03-29 12:33:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个Excel图表,我想用Python导出为图像。每个图表都在一个单独的Excel文件中,只有一张工作表。这个脚本几乎适用于我的所有图表:

import win32com.client as win32
from win32com.client import Dispatch

xl = Dispatch('Excel.Application')
xl.Visible = True
wb = xl.Workbooks.Open("C:\\test.xlsx")

xl.DisplayAlerts = False

chart = wb.Worksheets(1).ChartObjects(1)
chart.CopyPicture()   

#Create new temporary sheet (after first sheet)
xl.ActiveWorkbook.Sheets.Add(After=xl.ActiveWorkbook.Sheets(1)).Name="temp_sheet"
temp_sheet = xl.ActiveSheet

#Add chart object to new sheet.
cht = xl.ActiveSheet.ChartObjects().Add(0,0,chart.Width, chart.Height)

#Paste copied chart into new object
cht.Activate()      # dit is bij de topsheets nodig, anders plakt die een wit vlak... (bij trends en staafjes hoeft het niet)
cht.Chart.Paste()   

#Export image
cht.Chart.Export("C:\\test.png")

temp_sheet.Delete()
xl.ActiveWorkbook.Close()

#Restore default behaviour
xl.DisplayAlerts = True

我有一个图表,但不能导出。。。在导出函数之后,我得到了这个错误:

^{pr2}$

图表被复制到临时工作表中,但导出失败。在一些为导出此图表而编写的旧Excel VBA代码中,我看到以下行:

ActiveSheet.PasteSpecial Format:="Bitmap", Link:=False, 
DisplayAsIcon:=False

Python的等价物是什么?这个:

cht.Chart.PasteSpecial(Format="Bitmap")

不工作(AttributeError:“”对象没有属性“PasteSpecial”)

  • 编辑-

Xukrao的“剪贴板评论”为我指明了另一个方向。在本教程的帮助下,https://www.penwatch.net/cms/images_from_excel/我使用了PIL中的ImageGrab。正在导出图表!:)

import win32com.client as win32
from win32com.client import Dispatch

xl = Dispatch('Excel.Application')
xl.Visible = True
wb = xl.Workbooks.Open("C:\\test.xlsx")

xl.DisplayAlerts = False

chart = wb.Worksheets(1).ChartObjects(1)
chart.CopyPicture()   

#Create new temporary sheet (after first sheet)
xl.ActiveWorkbook.Sheets.Add(After=xl.ActiveWorkbook.Sheets(1)).Name="temp_sheet"
temp_sheet = xl.ActiveSheet

xl.ActiveSheet.PasteSpecial()

# Use PIL (python imaging library) to save from Windows clipboard
# to a file
wb.Worksheets(2).Pictures(1).Copy()
image = ImageGrab.grabclipboard()
image.save('blabla.bmp','bmp')

#This line is not entirely neccessary since script currently exits without 
saving
temp_sheet.Delete()
xl.ActiveWorkbook.Close()

#Restore default behaviour
xl.DisplayAlerts = True

Tags: fromimportclientchart图表exceltempwin32com