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

时间:2017-05-28 09:03:30

标签: python excel pywin32

我有几个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

我有一个图表,但无法导出...导出函数后出现此错误:

pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147287037), None)

图表将复制到临时工作表,但导出失败。在为导出此图表而编写的一些旧的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

1 个答案:

答案 0 :(得分:0)

直接Python相当于

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

就是这样:

xl.ActiveSheet.PasteSpecial(Format="Bitmap", Link=False, DisplayAsIcon=False)