
使用Python導(dǎo)出Excel圖表以及導(dǎo)出為圖片的方法
本篇講下如何使用純python代碼將excel 中的圖表導(dǎo)出為圖片。這里需要使用的模塊有win32com、pythoncom模塊。
網(wǎng)上經(jīng)查詢有人已經(jīng)寫好的模塊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另存為圖片篇中創(chuàng)建的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 中創(chuàng)建圖片,不過想實現(xiàn)將生成的chart圖表導(dǎo)出為圖片,在email
中導(dǎo)入圖片的目標(biāo) 。經(jīng)網(wǎng)上查詢未找到通過python代碼將excel 中已經(jīng)生成的圖片導(dǎo)出為圖片的方法,不過通過變通方法,使用excel
內(nèi)的vba 宏卻可以輕松將圖片導(dǎo)出。
1、導(dǎo)出單張圖片
python 創(chuàng)建chart圖片代碼:
#coding: utf-8
import xlsxwriter
import random
def get_num():
return random.randrange(0, 201, 2)
workbook = xlsxwriter.Workbook('analyse_spider.xlsx') #創(chuàng)建一個Excel文件
worksheet = workbook.add_worksheet() #創(chuàng)建一個工作表對象
chart = workbook.add_chart({'type': 'column'}) #創(chuàng)建一個圖表對象
#定義數(shù)據(jù)表頭列表
title = [u'業(yè)務(wù)名稱',u'星期一',u'星期二',u'星期三',u'星期四',u'星期五',u'星期六',u'星期日',u'平均流量']
buname= [u'運(yùn)維之路',u'就要IT',u'baidu.com',u'361way.com',u'91it.org'] #定義頻道名稱
#定義5頻道一周7天流量數(shù)據(jù)列表
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對象單元格內(nèi)容加粗的格式
format_ave=workbook.add_format() #定義format_ave格式對象
format_ave.set_border(1) #定義format_ave對象單元格邊框加粗(1像素)的格式
format_ave.set_num_format('0.00') #定義format_ave對象單元格數(shù)字類別顯示格式
#下面分別以行或列寫入方式將標(biāo)題、業(yè)務(wù)名稱、流量數(shù)據(jù)寫入起初單元格,同時引用不同格式對象
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)
#定義圖表數(shù)據(jù)系列函數(shù)
def chart_series(cur_row):
worksheet.write_formula('I'+cur_row, \
'=AVERAGE(B'+cur_row+':H'+cur_row+')',format_ave) #計算(AVERAGE函數(shù))頻
#道周平均流量
chart.add_series({
'categories': '=Sheet1!$B$1:$H$1', #將“星期一至星期日”作為圖表數(shù)據(jù)標(biāo)簽(X軸)
'values': '=Sheet1!$B$'+cur_row+':$H$'+cur_row, #頻道一周所有數(shù)據(jù)作
#為數(shù)據(jù)區(qū)域
'line': {'color': 'black'}, #線條顏色定義為black(黑色)
'name': '=Sheet1!$A$'+cur_row, #引用業(yè)務(wù)名稱為圖例項
})
for row in range(2, 7): #數(shù)據(jù)域以第2~6行進(jìn)行圖表數(shù)據(jù)系列函數(shù)調(diào)用
chart_series(str(row))
chart.set_size({'width': 577, 'height': 287}) #設(shè)置圖表大小
chart.set_title ({'name': u'爬蟲分析'}) #設(shè)置圖表(上方)大標(biāo)題
chart.set_y_axis({'name': 'count'}) #設(shè)置y軸(左側(cè))小標(biāo)題
worksheet.insert_chart('A8', chart) #在A8單元格插入圖表
workbook.close() #關(guān)閉Excel文檔
由于這里只有一張圖片,通過vba 代碼很容易生成圖片 。方法為,打開該excel 圖表,通過alt + F11 快捷鍵打開宏編輯界面;打開VB編輯器的立即窗口:”視圖“-”立即窗口“,或者使用快捷鍵"Ctrl + G" ,接著輸入如下代碼
activesheet.ChartObjects(1).Chart.Export "C:\chart.png"
按 " Enter " 鍵后,會在C盤生成上面的生成的chart圖表。
二、導(dǎo)出多張圖表
python代碼如下:
#coding: utf-8
import xlsxwriter
workbook = xlsxwriter.Workbook('chart_column.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': 1})
# 這是個數(shù)據(jù)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])
############################################
#創(chuàng)建一個圖表,類型是column
chart1 = workbook.add_chart({'type': 'column'})
# 配置series,這個和前面wordsheet是有關(guān)系的。
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()
同一數(shù)據(jù)源上面創(chuàng)建了三種類型的圖 ,由于有三張圖,上面的導(dǎo)出一張圖的方法肯定是不行了,這里打開宏,創(chuàng)建如下宏內(nèi)容:
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
該示例這里就不再截圖,具體可以自行運(yùn)行。
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
LSTM 模型輸入長度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動決策的時代浪潮下,CDA 數(shù)據(jù)分析師認(rèn)證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計的實用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強(qiáng)大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實施重大更新。 此次更新旨在確保認(rèn) ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡稱 BI)深度融合的時代,BI ...
2025-07-10SQL 在預(yù)測分析中的應(yīng)用:從數(shù)據(jù)查詢到趨勢預(yù)判? ? 在數(shù)據(jù)驅(qū)動決策的時代,預(yù)測分析作為挖掘數(shù)據(jù)潛在價值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點,而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報考到取證的全攻略? 在數(shù)字經(jīng)濟(jì)蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢性檢驗:捕捉數(shù)據(jù)背后的時間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢性檢驗如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認(rèn)證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗:數(shù)據(jù)趨勢與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢變化以及識別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認(rèn)證作為國內(nèi)權(quán)威的數(shù)據(jù)分析能力認(rèn)證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對策略? 長短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨特的門控機(jī)制,在 ...
2025-07-07統(tǒng)計學(xué)方法在市場調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場調(diào)研是企業(yè)洞察市場動態(tài)、了解消費者需求的重要途徑,而統(tǒng)計學(xué)方法則是市場調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03