xlwings,讓excel飛起來!

excel已經成爲必不可少的數據處理軟件,幾乎每天在用。python有不少支持操做excel的第三方庫,xlwings是其中一個。python

關於xlwings

xlwings開源免費,可以很是方便的讀寫Excel文件中的數據,而且可以進行單元格格式的修改。編程

xlwings還能夠和matplotlibnumpy以及pandas無縫鏈接,支持讀寫numpypandas的數據類型,將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語法簡單,功能強大,又很好結合了pandasnumpymatplotlib等分析庫,很是適合奔波於python和excel之間的童鞋,讓你更輕鬆地分析數據!


END


往期精選

 

geopandas,python畫地圖這麼簡單!

最全數據科學小抄,趕忙收藏吧!

教你如何使用Python製做酷炫二維碼

numba,讓python飛起來!
100行python代碼爬取豆瓣《哪吒》短評

教你如何使用Python下載全網視頻

小白如何入門Python爬蟲

那些鮮爲人知的優秀可視化庫

Python機器學習·微教程

小白入門Python數據科學全教程

什麼是matplotlib?

一文搞懂python匿名函數

一文讀懂Python的map、reduce函數

一文搞懂python迭代器和生成器



Python大數據分析

data creat value

長按二維碼關注

本文分享自微信公衆號 - Python大數據分析(pydatas)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索