我目前正试图使用win32com python库打开一个包含图表的excel文件,并将该图表保存为同一目录下的图片。
我尝试了下面的代码。
import win32com.client as win32
from win32com.client import Dispatch
import os
xlApp = win32.gencache.EnsureDispatch('Excel.Application')
# Open the workbook with the correct path
workbook = xlApp.Workbooks.Open("C:\\Users\\Owner\\PycharmProjects\\venv\\automaticexcelgrapherv4\\saveImageTest.xlsx")
xlApp.Sheets("Sheet1").Select()
xlApp.Visible = True
xlSheet1 = workbook.Sheets(1)
#Ensure to save any work before running script
xlApp.DisplayAlerts = False
i = 0
for chart in xlSheet1.ChartObjects():
chart.CopyPicture()
#Create new temporary sheet
xlApp.ActiveWorkbook.Sheets.Add(After=xlApp.ActiveWorkbook.Sheets(1)).Name="temp_sheet" + str(i)
temp_sheet = xlApp.ActiveSheet
#Add chart object to new sheet.
cht = xlApp.ActiveSheet.ChartObjects().Add(0,0,800, 600)
#Paste copied chart into new object
cht.Chart.Paste()
#Export image
#IMP: The next line exports the png image to the new sheet, however I would like to save it in the directory instead
cht.Chart.Export("chart" + str(i) + ".png")
i = i+1
xlApp.ActiveWorkbook.Close()
#Restore default behaviour
xlApp.DisplayAlerts = True
这将在excel文件中创建一个新的工作表 并将图表的.png图片放在里面。但是,我不知道如何再将该图片保存在该目录中。
导入后可以尝试用存储。
images = {}
with open(chartOne.png', 'rb') as x:
image = x.read()
images['MyImages'] = image
找到了一些类似的代码,经过一些修正后,就成功了。
import win32com.client
import PIL
from PIL import ImageGrab, Image
import os
import sys
inputExcelFilePath = "C:\\Users\\Owner\\PycharmProjects\\venv\\automaticexcelgrapherv4\\saveImageTest.xlsx"
outputPNGImagePath = "C:\\Users\\Owner\\PycharmProjects\\venv\\automaticexcelgrapherv4\\PreviewGraphAutomaticExcelGrapher.png"
# This function extracts a graph from the input excel file and saves it into the specified PNG image path (overwrites the given PNG image)
def saveExcelGraphAsPNG(inputExcelFilePath, outputPNGImagePath):
# Open the excel application using win32com
o = win32com.client.Dispatch("Excel.Application")
# Disable alerts and visibility to the user
o.Visible = 0
o.DisplayAlerts = 0
# Open workbook
wb = o.Workbooks.Open(inputExcelFilePath)
# Extract first sheet
sheet = o.Sheets(1)
for n, shape in enumerate(sheet.Shapes):
# Save shape to clipboard, then save what is in the clipboard to the file
shape.Copy()
image = ImageGrab.grabclipboard()
# Saves the image into the existing png file (overwriting) TODO ***** Have try except?
image.save(outputPNGImagePath, 'png')
pass
pass
wb.Close(True)
o.Quit()
saveExcelGraphAsPNG(inputExcelFilePath, outputPNGImagePath)
这个函数输入的是一个包含一个图表的excel文件的路径(或者多个,在这种情况下,它会选择最后一个)和一个现有的PNG图片的路径,然后覆盖它,把图表放在里面。