gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:08:11 25 4
gpt4 key购买 nike

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

最佳答案

Python 的直接等价物

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

会是这样的:

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

关于Python win32 Excel 将图表粘贴为位图 (PasteSpecial)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44225524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com