如何从excel导出图表作为图像并使用python保存该图像?

时间:2017-12-01 06:56:02

标签: excel python-3.x outlook-2010

我想从excel电子表格中复制图表,并使用python将其保存为我的硬盘上的图像。 在那之后我想通过电子邮件正面的那个图片过去。

1 个答案:

答案 0 :(得分:0)

import datetime
import win32com.client as win32
from win32com.client import Dispatch
from PIL import ImageGrab # for this module you should have "Download Windows x86-64 executable installer" You can download it from link:-https://www.python.org/downloads/windows/ 
import os

#Creating object for an excel application. So that we can access and work on it.
xlApp = Dispatch('Excel.Application')

# To open existing spread sheet.
workbook = xlApp.Workbooks.Open(r'D:\Script\How to mail\Sigos_DailyHealthCheckReport.xlsx')

# Function 1 :-
def capture_image(worksheet_name,name_of_image): #worksheet_name :- from which worksheet you want to pick a chart . name_of_image:- what name you want to save it as image.

    #To select particular worksheet of the workbook by name.
    xlApp.Sheets(worksheet_name).Select()

    # To create an object for the worksheet.
    xlSheet1 = xlApp.Sheets(worksheet_name)

    #WARNING: The following line will cause the script to discard any unsaved changes in your workbook
    #Ensure to save any work before running script
    xlApp.DisplayAlerts = False

    i =0
    # "chart" will capture all the charts available in the seleted worksheet.
    for chart in xlSheet1.ChartObjects():
        print (chart.Name)
        chart.CopyPicture()

        #Create new temporary sheet
        xlApp.ActiveWorkbook.Sheets.Add(After=xlApp.ActiveWorkbook.Sheets(3)).Name="temp_sheet" + str(i)

        # To create an object for the worksheet.
        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
        #cht.Chart.Export("chart" + str(i) + ".png")



    #Provide a range in which the image need to be copied from the temporary worksheet.
    temp_sheet.Range(temp_sheet.Cells(1,1),temp_sheet.Cells(1,1)).CopyPicture()

    #It will capture copied image from the clipboard and assign that to img variable.
    img = ImageGrab.grabclipboard()
    if img is None:
       print('Error: No image data in clipboard')

    #we will provide address and name to which the immage need to be saved.
    imgFile = os.path.join(r'D:\Script\How to mail',name_of_image)
    img.save(imgFile)

    #Delete the temporary worksheet when chart image is capture.
    temp_sheet.Delete()