【问题标题】:How can I save an excel chart as an image using python?如何使用python将excel图表保存为图像?
【发布时间】:2020-05-07 12:21:30
【问题描述】:

我目前正在尝试使用 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 图像放入其中。但是,我不知道如何将该图像保存在目录中。

【问题讨论】:

    标签: python excel win32com pywin


    【解决方案1】:

    导出后您可以尝试存储:

    images = {}
    with open(chartOne.png', 'rb') as x:
        image = x.read()
        images['MyImages'] = image
    

    【讨论】:

    • 当我运行它时,它说目录中没有这样的文件:'chartOne.png'。此代码是否从目录中的图像读取?因为我希望它从excel文件中复制图像并将其保存到目录中。
    • chartOne.png - 我给出的示例如下:您的图片名称:“chart”+str(i)+“.png”
    【解决方案2】:

    找到了一些类似的代码,经过一番修复后,它工作了:

    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 图像的路径作为输入,然后覆盖该路径以将图形放入其中.

    【讨论】:

      【解决方案3】:

      跟进@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。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多