本篇讲下如何使用纯python代码将excel 中的图表导出为图片。这里需要使用的模块有win32com、pythoncom模块。
网上经查询有人已经写好的模块pyxlchart,具体代码如下:
from win32com.client import dispatch
import os
import pythoncom
class pyxlchart(object):
“””
this class exports charts in an excel spreadsheet to the filesystem
win32com libraries are required.
“””
def __init__(self):
pythoncom.coinitialize()
self.workbookdirectory = ”
self.workbookfilename = ”
self.getallworkbooks = false
self.sheetname = ”
self.chartname = ”
self.getallworkbookcharts = false
self.getallworksheetcharts = false
self.exportpath = ”
self.imagefilename = ”
self.replacewhitespacechar = ‘_’
self.imagetype = ‘jpg’
def __del__(self):
pass
def start_export(self):
if self.workbookdirectory == ”:
return “workbookdirectory not set”
else:
self._export()
def _export(self):
“””
exports charts as determined by the settings in class variabels.
“””
excel = dispatch(“excel.application”)
excel.visible = false
wb = excel.workbooks.open(os.path.join(self.workbookdirectory ,self.workbookfilename))
self._get_charts_in_worksheet(wb,self.sheetname,self.chartname)
wb.close(false)
excel.quit()
def _get_charts_in_worksheet(self,wb,worksheet = “”, chartname = “”):
if worksheet != “” and chartname != “”:
sht = self._change_sheet(wb,worksheet)
cht = sht.chartobjects(chartname)
self._save_chart(cht)
return
if worksheet == “”:
for sht in wb.worksheets:
for cht in sht.chartobjects():
if chartname == “”:
self._save_chart(cht)
else:
if chartname == cht.name:
self._save_chart(cht)
else:
sht = wb.worksheets(worksheet)
for cht in sht.chartobjects():
if chartname == “”:
self._save_chart(cht)
else:
if chartname == cht.name:
self._save_chart(cht)
def _change_sheet(self,wb,worksheet):
try:
return wb.worksheets(worksheet)
except:
raise nameerror(‘unable to select sheet: ‘ + worksheet + ‘ in workbook: ‘ + wb.name)
def _save_chart(self,chartobject):
imagename = self._get_filename(chartobject.name)
savepath = os.path.join(self.exportpath,imagename)
print savepath
chartobject.chart.export(savepath,self.imagetype)
def _get_filename(self,chartname):
“””
replaces white space in self.workbookfilename with the value given in self.replacewhitespacechar
if self.replacewhitespacechar is an empty string then self.workbookfilename is left as is
“””
if self.imagefilename == ”:
self.imagefilename == chartname
if self.replacewhitespacechar != ”:
chartname.replace(‘ ‘,self.replacewhitespacechar)
if self.imagefilename != “”:
return self.imagefilename + “_” + chartname + “.” + self.imagetype
else:
return chartname + ‘.’ + self.imagetype
if __name__ == “__main__”:
xl = pyxlchart()
xl.workbookdirectory = “\\\\maawtns01\\discipline\\procurement\\materiel\\raw material\\data management\\hawk”
xl.workbookfilename = “hawk workability kpi.xlsm”
xl.sheetname = “”
xl.imagefilename = “mychart1”
xl.exportpath = “d:\\pycharts”
xl.chartname = “”
xl.start_export()
print “this file does not currently allow direct access”
print “please import pyxlchart and run start_export()”
这里还使用excel vba将chart另存为图片篇中创建的chart_column.xlsx表,使用上面的模块的方法如下:
from pyxlchart import pyxlchart
xl = pyxlchart()
xl.workbookdirectory = “d:\\”
xl.workbookfilename = “chart_column.xlsx”
xl.sheetname = “”
#xl.imagefilename = “mychart1”
xl.exportpath = “d:\\”
xl.chartname = “”
xl.start_export()
由于有该表里有多张图表,所以上面未指定xl.imagefilename ,使用示例如下:
excel vba将chart另存为图片
python下使用xlswriter模块,可以轻松在excel 中创建图片,不过想实现将生成的chart图表导出为图片,在email 中导入图片的目标 。经网上查询未找到通过python代码将excel 中已经生成的图片导出为图片的方法,不过通过变通方法,使用excel 内的vba 宏却可以轻松将图片导出。
1、导出单张图片
python 创建chart图片代码:
#coding: utf-8
import xlsxwriter
import random
def get_num():
return random.randrange(0, 201, 2)
workbook = xlsxwriter.workbook(‘analyse_spider.xlsx’) #创建一个excel文件
worksheet = workbook.add_worksheet() #创建一个工作表对象
chart = workbook.add_chart({‘type’: ‘column’}) #创建一个图表对象
#定义数据表头列表
title = [u’业务名称’,u’星期一’,u’星期二’,u’星期三’,u’星期四’,u’星期五’,u’星期六’,u’星期日’,u’平均流量’]
buname= [u’运维之路’,u’就要it’,u’baidu.com’,u’361way.com’,u’91it.org’] #定义频道名称
#定义5频道一周7天流量数据列表
data = []
for i in range(5):
tmp = []
for j in range(7):
tmp.append(get_num())
data.append(tmp)
format=workbook.add_format() #定义format格式对象
format.set_border(1) #定义format对象单元格边框加粗(1像素)的格式
format_title=workbook.add_format() #定义format_title格式对象
format_title.set_border(1) #定义format_title对象单元格边框加粗(1像素)的格式
format_title.set_bg_color(‘#cccccc’) #定义format_title对象单元格背景颜色为
#’#cccccc’的格式
format_title.set_align(‘center’) #定义format_title对象单元格居中对齐的格式
format_title.set_bold() #定义format_title对象单元格内容加粗的格式
format_ave=workbook.add_format() #定义format_ave格式对象
format_ave.set_border(1) #定义format_ave对象单元格边框加粗(1像素)的格式
format_ave.set_num_format(‘0.00’) #定义format_ave对象单元格数字类别显示格式
#下面分别以行或列写入方式将标题、业务名称、流量数据写入起初单元格,同时引用不同格式对象
worksheet.write_row(‘a1’,title,format_title)
worksheet.write_column(‘a2’, buname,format)
worksheet.write_row(‘b2’, data[0],format)
worksheet.write_row(‘b3’, data[1],format)
worksheet.write_row(‘b4’, data[2],format)
worksheet.write_row(‘b5’, data[3],format)
worksheet.write_row(‘b6’, data[4],format)
#定义图表数据系列函数
def chart_series(cur_row):
worksheet.write_formula(‘i’+cur_row, \
‘=average(b’+cur_row+’:h’+cur_row+’)’,format_ave) #计算(average函数)频
#道周平均流量
chart.add_series({
‘categories’: ‘=sheet1!$b$1:$h$1’, #将“星期一至星期日”作为图表数据标签(x轴)
‘values’: ‘=sheet1!$b$’+cur_row+’:$h$’+cur_row, #频道一周所有数据作
#为数据区域
‘line’: {‘color’: ‘black’}, #线条颜色定义为black(黑色)
‘name’: ‘=sheet1!$a$’+cur_row, #引用业务名称为图例项
})
for row in range(2, 7): #数据域以第2~6行进行图表数据系列函数调用
chart_series(str(row))
chart.set_size({‘width’: 577, ‘height’: 287}) #设置图表大小
chart.set_title ({‘name’: u’爬虫分析’}) #设置图表(上方)大标题
chart.set_y_axis({‘name’: ‘count’}) #设置y轴(左侧)小标题
worksheet.insert_chart(‘a8’, chart) #在a8单元格插入图表
workbook.close() #关闭excel文档
由于这里只有一张图片,通过vba 代码很容易生成图片 。方法为,打开该excel 图表,通过alt + f11 快捷键打开宏编辑界面;打开vb编辑器的立即窗口:”视图“-”立即窗口“,或者使用快捷键”ctrl + g” ,接着输入如下代码
activesheet.chartobjects(1).chart.export “c:\chart.png”
按 ” enter ” 键后,会在c盘生成上面的生成的chart图表。
二、导出多张图表
python代码如下:
#coding: utf-8
import xlsxwriter
workbook = xlsxwriter.workbook(‘chart_column.xlsx’)
worksheet = workbook.add_worksheet()
bold = workbook.add_format({‘bold’: 1})
# 这是个数据table的列
headings = [‘number’, ‘batch 1’, ‘batch 2’]
data = [
[2, 3, 4, 5, 6, 7],
[10, 40, 50, 20, 10, 50],
[30, 60, 70, 50, 40, 30],
]
worksheet.write_row(‘a1’, headings, bold)
worksheet.write_column(‘a2’, data[0])
worksheet.write_column(‘b2’, data[1])
worksheet.write_column(‘c2’, data[2])
############################################
#创建一个图表,类型是column
chart1 = workbook.add_chart({‘type’: ‘column’})
# 配置series,这个和前面wordsheet是有关系的。
chart1.add_series({
‘name’: ‘=sheet1!$b$1’,
‘categories’: ‘=sheet1!$a$2:$a$7’,
‘values’: ‘=sheet1!$b$2:$b$7’,
})
# configure a second series. note use of alternative syntax to define ranges.
chart1.add_series({
‘name’: [‘sheet1’, 0, 2],
‘categories’: [‘sheet1’, 1, 0, 6, 0],
‘values’: [‘sheet1’, 1, 2, 6, 2],
})
# add a chart title and some axis labels.
chart1.set_title ({‘name’: ‘results of sample analysis’})
chart1.set_x_axis({‘name’: ‘test number’})
chart1.set_y_axis({‘name’: ‘sample length (mm)’})
# set an excel chart style.
chart1.set_style(11)
# insert the chart into the worksheet (with an offset).
worksheet.insert_chart(‘d2’, chart1, {‘x_offset’: 25, ‘y_offset’: 10})
#######################################################################
#
# create a stacked chart sub-type.
#
chart2 = workbook.add_chart({‘type’: ‘column’, ‘subtype’: ‘stacked’})
# configure the first series.
chart2.add_series({
‘name’: ‘=sheet1!$b$1’,
‘categories’: ‘=sheet1!$a$2:$a$7’,
‘values’: ‘=sheet1!$b$2:$b$7’,
})
# configure second series.
chart2.add_series({
‘name’: ‘=sheet1!$c$1’,
‘categories’: ‘=sheet1!$a$2:$a$7’,
‘values’: ‘=sheet1!$c$2:$c$7’,
})
# add a chart title and some axis labels.
chart2.set_title ({‘name’: ‘stacked chart’})
chart2.set_x_axis({‘name’: ‘test number’})
chart2.set_y_axis({‘name’: ‘sample length (mm)’})
# set an excel chart style.
chart2.set_style(12)
# insert the chart into the worksheet (with an offset).
worksheet.insert_chart(‘d18’, chart2, {‘x_offset’: 25, ‘y_offset’: 10})
#######################################################################
#
# create a percentage stacked chart sub-type.
#
chart3 = workbook.add_chart({‘type’: ‘column’, ‘subtype’: ‘percent_stacked’})
# configure the first series.
chart3.add_series({
‘name’: ‘=sheet1!$b$1’,
‘categories’: ‘=sheet1!$a$2:$a$7’,
‘values’: ‘=sheet1!$b$2:$b$7’,
})
# configure second series.
chart3.add_series({
‘name’: ‘=sheet1!$c$1’,
‘categories’: ‘=sheet1!$a$2:$a$7’,
‘values’: ‘=sheet1!$c$2:$c$7’,
})
# add a chart title and some axis labels.
chart3.set_title ({‘name’: ‘percent stacked chart’})
chart3.set_x_axis({‘name’: ‘test number’})
chart3.set_y_axis({‘name’: ‘sample length (mm)’})
# set an excel chart style.
chart3.set_style(13)
# insert the chart into the worksheet (with an offset).
worksheet.insert_chart(‘d34’, chart3, {‘x_offset’: 25, ‘y_offset’: 10})
workbook.close()
同一数据源上面创建了三种类型的图 ,由于有三张图,上面的导出一张图的方法肯定是不行了,这里打开宏,创建如下宏内容:
sub exportimg()
dim xlschart as chartobject
for each xlschart in worksheets(“sheet1″).chartobjects
xlschart.chart.export filename:=”c:\” & xlschart.name & “.jpg”, filtername:=”jpg”
next
end sub
该示例这里就不再截图,具体可以自行运行。