下载:需要先安装pywin32com 和 comtypes
下载地址:(用来下载三个packages)
https://pypi.org/project/
在官网搜索就可以下载到
然后放到Scripts下安装
务必先安装pywin32com 和 comtypes ,最后安装xlwings
import xlwings as xls
newbook = xls.Book() # this will create a new workbook
会打开一个如下,nothing else
wb = xls.Book(r"D:\中雅兼职资料\待办总.xlsx") # connect to an existing file in the current working directory
会打开所展示的xlsx文件,仅打开而已
sht = wb.sheets['待办1号']
读取相应工作表
sht.range('A50').value = 'Foo 1'
设置单元格值(并未自动保存)
sht.range('A50').value = [['Foo 1', 'Foo 2', 'Foo 3'], [10.0, 20.0, 30.0]]
扩展:50行填入['Foo 1', 'Foo 2', 'Foo 3']
51行填入[10.0, 20.0, 30.0]
>>> sht.range('A1').value = [[1],[2],[3],[4],[5]] # Column orientation (nested list) >>> sht.range('A1:A5').value [1.0, 2.0, 3.0, 4.0, 5.0] >>> sht.range('A1').value = [1, 2, 3, 4, 5] >>> sht.range('A1:E1').value [1.0, 2.0, 3.0, 4.0, 5.0]
列表的每一个子列表,都表示一行
To write a list in column orientation to Excel, use transpose
: sht.range('A1').options(transpose=True).value = [1,2,3,4]
相当于 [[1],[2],[3],[4],[5]] 结果:>> sht.range('A1:A5').value [1.0, 2.0, 3.0, 4.0, 5.0]
region = sht.range('A1:C3').value
赋值region列表List
关于区域拓展:
sht.range('A1').expand().value
将会表示与A1相连且连续的所有单元格
还有一些与其他package合作的功能,详见https://docs.xlwings.org/zh_CN/latest/quickstart.html
2d lists: If the row or column orientation has to be preserved, set ndim
in the Range options. This will return the Ranges as nested lists (“2d lists”):
>>> sht.range('A1:A5').options(ndim=2).value [[1.0], [2.0], [3.0], [4.0], [5.0]] >>> sht.range('A1:E1').options(ndim=2).value [[1.0, 2.0, 3.0, 4.0, 5.0]]
如何在读取值的时候更直观的呈现出来?令options(ndim=2)