
使用Python導出Excel圖表以及導出為圖片的方法
本篇講下如何使用純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
該示例這里就不再截圖,具體可以自行運行。
數據分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
CDA數據分析師證書考試體系(更新于2025年05月22日)
2025-05-26解碼數據基因:從數字敏感度到邏輯思維 每當看到超市貨架上商品的排列變化,你是否會聯想到背后的銷售數據波動?三年前在零售行 ...
2025-05-23在本文中,我們將探討 AI 為何能夠加速數據分析、如何在每個步驟中實現數據分析自動化以及使用哪些工具。 數據分析中的AI是什么 ...
2025-05-20當數據遇見人生:我的第一個分析項目 記得三年前接手第一個數據分析項目時,我面對Excel里密密麻麻的銷售數據手足無措。那些跳動 ...
2025-05-20在數字化運營的時代,企業每天都在產生海量數據:用戶點擊行為、商品銷售記錄、廣告投放反饋…… 這些數據就像散落的拼圖,而相 ...
2025-05-19在當今數字化營銷時代,小紅書作為國內領先的社交電商平臺,其銷售數據蘊含著巨大的商業價值。通過對小紅書銷售數據的深入分析, ...
2025-05-16Excel作為最常用的數據分析工具,有沒有什么工具可以幫助我們快速地使用excel表格,只要輕松幾步甚至輸入幾項指令就能搞定呢? ...
2025-05-15數據,如同無形的燃料,驅動著現代社會的運轉。從全球互聯網用戶每天產生的2.5億TB數據,到制造業的傳感器、金融交易 ...
2025-05-15大數據是什么_數據分析師培訓 其實,現在的大數據指的并不僅僅是海量數據,更準確而言是對大數據分析的方法。傳統的數 ...
2025-05-14CDA持證人簡介: 萬木,CDA L1持證人,某電商中廠BI工程師 ,5年數據經驗1年BI內訓師,高級數據分析師,擁有豐富的行業經驗。 ...
2025-05-13CDA持證人簡介: 王明月 ,CDA 數據分析師二級持證人,2年數據產品工作經驗,管理學博士在讀。 學習入口:https://edu.cda.cn/g ...
2025-05-12CDA持證人簡介: 楊貞璽 ,CDA一級持證人,鄭州大學情報學碩士研究生,某上市公司數據分析師。 學習入口:https://edu.cda.cn/g ...
2025-05-09CDA持證人簡介 程靖 CDA會員大咖,暢銷書《小白學產品》作者,13年頂級互聯網公司產品經理相關經驗,曾在百度、美團、阿里等 ...
2025-05-07相信很多做數據分析的小伙伴,都接到過一些高階的數據分析需求,實現的過程需要用到一些數據獲取,數據清洗轉換,建模方法等,這 ...
2025-05-06以下的文章內容來源于劉靜老師的專欄,如果您想閱讀專欄《10大業務分析模型突破業務瓶頸》,點擊下方鏈接 https://edu.cda.cn/g ...
2025-04-30CDA持證人簡介: 邱立峰 CDA 數據分析師二級持證人,數字化轉型專家,數據治理專家,高級數據分析師,擁有豐富的行業經驗。 ...
2025-04-29CDA持證人簡介: 程靖 CDA會員大咖,暢銷書《小白學產品》作者,13年頂級互聯網公司產品經理相關經驗,曾在百度,美團,阿里等 ...
2025-04-28CDA持證人簡介: 居瑜 ,CDA一級持證人國企財務經理,13年財務管理運營經驗,在數據分析就業和實踐經驗方面有著豐富的積累和經 ...
2025-04-27數據分析在當今信息時代發揮著重要作用。單因素方差分析(One-Way ANOVA)是一種關鍵的統計方法,用于比較三個或更多獨立樣本組 ...
2025-04-25CDA持證人簡介: 居瑜 ,CDA一級持證人國企財務經理,13年財務管理運營經驗,在數據分析就業和實踐經驗方面有著豐富的積累和經 ...
2025-04-25