excel已經成爲必不可少的數據處理軟件,幾乎每天在用。python有不少支持操做excel的第三方庫,xlwings
是其中一個。python
關於xlwings
xlwings
開源免費,可以很是方便的讀寫Excel文件中的數據,而且可以進行單元格格式的修改。編程
xlwings
還能夠和matplotlib
、numpy
以及pandas
無縫鏈接,支持讀寫numpy
、pandas
的數據類型,將matplotlib
可視化圖表導入到excel中。windows
最重要的是xlwings
能夠調用Excel文件中VBA寫好的程序,也可讓VBA調用用Python寫的程序。微信
話很少說,咱們開始練一練吧!機器學習
xlwings安裝和導入
本文python版本爲3.6,系統環境爲windows,在jupyter notebook中進行實驗。xlwings
庫使用pip
安裝:函數
pip install xlwings
xlwings
導入:學習
import xlwings as xw
xlwings實操
創建excel錶鏈接大數據
wb = xw.Book("e:\example.xlsx")
實例化工做表對象spa
sht = wb.sheets["sheet1"]
返回工做表絕對路徑.net
wb.fullname
返回工做簿的名字
sht.name
在單元格中寫入數據
sht.range('A1').value = "xlwings"
讀取單元格內容
sht.range('A1').value
清除單元格內容和格式
sht.range('A1').clear()
獲取單元格的列標
sht.range('A1').column
獲取單元格的行標
sht.range('A1').row
獲取單元格的行高
sht.range('A1').row_height
獲取單元格的列寬
sht.range('A1').column_width
列寬自適應
sht.range('A1').columns.autofit()
行高自適應
sht.range('A1').rows.autofit()
給單元格上背景色,傳入RGB值
sht.range('A1').color = (34,139,34)
獲取單元格顏色,RGB值
sht.range('A1').color
清除單元格顏色
sht.range('A1').color = None
輸入公式,相應單元格會出現計算結果
sht.range('A1').formula='=SUM(B6:B7)'
獲取單元格公式
sht.range('A1').formula_array
在單元格中寫入批量數據,只須要指定其實單元格位置便可
sht.range('A2').value = [['Foo 1', 'Foo 2', 'Foo 3'], [10.0, 20.0, 30.0]]
讀取表中批量數據,使用expand()方法
sht.range('A2').expand().value
其實你也能夠不指定工做表的地址,直接與電腦裏的活動表格進行交互
# 寫入xw.Range("E1").value = "xlwings"# 讀取xw.Range("E1").value
xlwings與numpy、pandas、matplotlib互動
支持寫入
numpy array
數據類型
import numpy as np
np_data = np.array((1,2,3))
sht.range('F1').value = np_data
支持將
pandas DataFrame
數據類型寫入excel
import pandas as pd
df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
sht.range('A5').value = df
將數據讀取,輸出類型爲
DataFrame
sht.range('A5').options(pd.DataFrame,expand='table').value
將
matplotlib
圖表寫入到excel表格裏
import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure()
plt.plot([1, 2, 3, 4, 5])
sht.pictures.add(fig, name='MyPlot', update=True)
xlwings與VBA互相調用
xlwings
與VBA的配合很是完美,你能夠在python中調用VBA,也能夠在VBA中使用python編程,這些經過xlwings
均可以巧妙實現。這裏不對該內容作詳細講解,感興趣的童鞋能夠去xlwings
官網學習。
總結
xlwings
操做excel語法簡單,功能強大,又很好結合了pandas
、numpy
、matplotlib
等分析庫,很是適合奔波於python和excel之間的童鞋,讓你更輕鬆地分析數據!
![](http://static.javashuo.com/static/loading.gif)
END
往期精選
Python大數據分析
data creat value
![](http://static.javashuo.com/static/loading.gif)
長按二維碼關注
本文分享自微信公衆號 - Python大數據分析(pydatas)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。