Excel vba将chart另存为图片篇中讲了如何通过vba宏将excel 中的chart图表导出为的图片,本篇讲下如何使用纯python代码将excel 中的图表导出为图片。这里需要使用的模块有win32com、pythoncom模块。

网上经查询有人已经写好的模块pyxlchart,具体代码如下:

 1from win32com.client import Dispatch
 2import os
 3import pythoncom
 4class Pyxlchart(object):
 5    """
 6    This class exports charts in an Excel Spreadsheet to the FileSystem
 7    win32com libraries are required.
 8    """
 9    def __init__(self):
10        pythoncom.CoInitialize()
11        self.WorkbookDirectory = ''
12        self.WorkbookFilename = ''
13        self.GetAllWorkbooks = False
14        self.SheetName = ''
15        self.ChartName = ''
16        self.GetAllWorkbookCharts = False
17        self.GetAllWorksheetCharts = False
18        self.ExportPath = ''
19        self.ImageFilename = ''
20        self.ReplaceWhiteSpaceChar = '_'
21        self.ImageType = 'jpg'
22    def __del__(self):
23        pass
24    def start_export(self):
25        if self.WorkbookDirectory == '':
26            return "WorkbookDirectory not set"
27        else:
28            self._export()
29    def _export(self):
30        """
31        Exports Charts as determined by the settings in class variabels.
32        """
33        excel = Dispatch("excel.application")
34        excel.Visible = False
35        wb = excel.Workbooks.Open(os.path.join(self.WorkbookDirectory ,self.WorkbookFilename))
36        self._get_Charts_In_Worksheet(wb,self.SheetName,self.ChartName)
37        wb.Close(False)
38        excel.Quit()
39    def _get_Charts_In_Worksheet(self,wb,worksheet = "", chartname = ""):
40        if worksheet != "" and chartname != "":
41            sht = self._change_sheet(wb,worksheet)
42            cht = sht.ChartObjects(chartname)
43            self._save_chart(cht)
44            return
45        if worksheet == "":
46            for sht in wb.Worksheets:
47                for cht in sht.ChartObjects():
48                    if chartname == "":
49                        self._save_chart(cht)
50                    else:
51                        if chartname == cht.Name:
52                            self._save_chart(cht)
53        else:
54            sht = wb.Worksheets(worksheet)
55            for cht in sht.ChartObjects():
56                if chartname == "":
57                    self._save_chart(cht)
58                else:
59                    if chartname == cht.Name:
60                        self._save_chart(cht)
61    def _change_sheet(self,wb,worksheet):
62        try:
63            return wb.Worksheets(worksheet)
64        except:
65            raise NameError('Unable to Select Sheet: ' + worksheet + ' in Workbook: ' + wb.Name)
66    def _save_chart(self,chartObject):
67        imagename = self._get_filename(chartObject.Name)
68        savepath = os.path.join(self.ExportPath,imagename)
69        print savepath
70        chartObject.Chart.Export(savepath,self.ImageType)
71    def _get_filename(self,chartname):
72        """
73        Replaces white space in self.WorkbookFileName with the value given in self.ReplaceWhiteSpaceChar
74        If self.ReplaceWhiteSpaceChar is an empty string then self.WorkBookFileName is left as is
75        """
76        if self.ImageFilename == '':
77            self.ImageFilename == chartname
78        if self.ReplaceWhiteSpaceChar != '':
79            chartname.replace(' ',self.ReplaceWhiteSpaceChar)
80        if self.ImageFilename != "":
81            return self.ImageFilename + "_" + chartname + "." + self.ImageType
82        else:
83            return chartname + '.' + self.ImageType
84if __name__ == "__main__":
85    xl = Pyxlchart()
86    xl.WorkbookDirectory = "\\\\maawtns01\\discipline\\procurement\\MATERIEL\\Raw Material\\Data Management\\Hawk"
87    xl.WorkbookFilename = "Hawk Workability KPI.xlsm"
88    xl.SheetName = ""
89    xl.ImageFilename = "MyChart1"
90    xl.ExportPath = "d:\\pycharts"
91    xl.ChartName = ""
92    xl.start_export()
93    print "This file does not currently allow direct access"
94    print "Please import PyXLChart and run start_export()"

这里还使用Excel vba将chart另存为图片篇中创建的chart_column.xlsx表,使用上面的模块的方法如下:

1from pyxlchart import Pyxlchart
2xl = Pyxlchart()
3xl.WorkbookDirectory = "D:\\"
4xl.WorkbookFilename = "chart_column.xlsx"
5xl.SheetName = ""
6#xl.ImageFilename = "MyChart1"
7xl.ExportPath = "d:\\"
8xl.ChartName = ""
9xl.start_export()

由于有该表里有多张图表,所以上面未指定xl.ImageFilename ,使用示例如下:

python-export-charts.png