excel已经成为必不可少的数据处理软件,几乎天天在用。python有很多支持操作excel的第三方库,xlwings 是其中一个。 关于xlwingsxlwings 开源免费,能够非常方便的读写Excel文件中的数据,并且能够进行单元格格式的修改。
xlwings 还可以和matplotlib 、numpy 以及pandas 无缝连接,支持读写numpy 、pandas 的数据类型,将matplotlib 可视化图表导入到excel中。
最重要的是xlwings 可以调用Excel文件中VBA写好的程序,也可以让VBA调用用Python写的程序。 话不多说,我们开始练一练吧! xlwings安装和导入本文python版本为3.6,系统环境为windows,在jupyter notebook中进行实验。
xlwings 库使用pip 安装: pip install xlwings
xlwings 导入:
import xlwings as xw
xlwings实操
wb = xw.Book("e:\example.xlsx")
sht = wb.sheets["sheet1"]
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()
sht.range('A1').color = (34,139,34)
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]]
sht.range('A2').expand().value
# 写入xw.Range("E1").value = "xlwings"# 读取xw.Range("E1").value
xlwings与numpy、pandas、matplotlib互动import numpy as np np_data = np.array((1,2,3)) sht.range('F1').value = np_data
import pandas as pd df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b']) sht.range('A5').value = df
sht.range('A5').options(pd.DataFrame,expand='table').value
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之间的童鞋,让你更轻松地分析数据!
Python大数据分析 data creat value
|