如何使用 python 将 excel 图表保存为图像?

How can I save an excel chart as an image using python?

我目前正在尝试使用 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 文件中创建一个新的 sheet 并将图表的 .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)

该函数将包含一个图形(或多个图形,在这种情况下它将 select 最后一个)的 excel 文件的路径和现有 PNG 的路径作为输入然后覆盖图像以将图形放入其中。

跟进@nernac 的回答。您的代码只需稍作修改即可将所有 excel 个对象保存到图像中:

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\"

# 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()
        length_x, width_y = image.size
        size = int(factor * length_x), int(factor * width_y)
        image_resize = image.resize(size, Image.ANTIALIAS)
        # Saves the image into the existing png file (overwriting) TODO ***** Have try except?
        outputPNGImage = outputPNGImagePath + str(n) + '.jpeg'
        image_resize.save(outputPNGImage, 'JPEG', quality=95, dpi=(300, 300))
        pass
    pass

    wb.Close(True)
    o.Quit()

saveExcelGraphAsPNG(inputExcelFilePath, outputPNGImagePath)

我还添加了线条来调整图像的大小和分辨率。这适用于 Python 3.7.