pip install xlwings
或
conda install xlwings
import xlwings as xw
wb = xw.Book() # 创建新的工作簿
# wb = xw.Book('FileName.xlsx') # 连接当前工作路径的工作簿
# wb = xw.Book(r'C:\path\to\file.xlsx') # Windows下用raw string构建路径连接指定工作簿
sht = wb.sheets['Sheet1']
sht.range('A1').value = 'Foo 1'
print(sht.range('A1').value) # Foo 1
甚至可以扩展范围
sht.range('A1').value = [['Foo 1', 'Foo 2', 'Foo 3'], [10.0, 20.0, 30.0]]
print(sht.range('A1').expand().value) # [['Foo 1', 'Foo 2', 'Foo 3'], [10.0, 20.0, 30.0]]
看一下效果
wb.save('test.xlsx')
强力的转换器能处理互联网中的绝大多数数据类型,包括Numpy arrays和Pandas DataFrames
import pandas as pd
df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
sht.range('A1').value = df
print(sht.range('A1').options(pd.DataFrame, expand='table').value)
a b
0.0 1.0 2.0
1.0 3.0 4.0
Matplotlib的图像也能在Excel中出现
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot([1, 2, 3, 4, 5])
sht.pictures.add(fig, name='MyPlot', update=True)
wb.save('test.xlsx')
wb.close()
import os
import xlwings as xw
wb = xw.Book()
sht = wb.sheets['Sheet1']
# sht.pictures.add('1.jpg') # 使用相对路径会报错,xlwings版本0.15.8下
sht.pictures.add(os.path.join(os.getcwd(), '1.jpg'))
wb.save('test.xlsx')
wb.close()
可指定位置和大小,具体见:https://blog.csdn.net/lly1122334/article/details/100160206