Python的Win32 Excel粘贴图表位图(PasteSpecial)?

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

我有一个图表,但无法导出…我得到这个错误后,出口function:

 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')

  • 编辑 –

徐克劳的“剪贴板评论”指出了另一个方向。 在本教程的帮助下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 

Python的直接等价物

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

会是这样的:

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