在Windows平台上,还可以通过 Excel 应用的 COM 接口 来对Excel进行操作。
这个方法相当于使用Python程序 通过 Excel应用 自己去修改,当然没有任何的副作用
而且能够实现一些特殊的功能,比如 自动打印Excel、合并单元格 等。
COM接口的特点是:打开文件快,读写速度慢。
使用 Excel COM 接口 打开 超大
Excel文件 比上面的两个库 要快很多。因为Excel程序本身的优化,可以部分加载,而上面的两个库是全部先读入内存。
如果你只是从 大Excel文件中 读取或修改少量数据,Excel COM 接口会快很多。
但是,如果你要读取大Excel中的大量数据,不要使用 COM接口,会非常的慢。
使用 Excel COM 接口,首先需要安装pywin32库,在命令行窗口输入如下命令:
pip install pywin32
比如可以这样修改
import win32com.client
excel = win32com.client.Dispatch("Excel.Application")
# excel.Visible = True # 可以让excel 可见
# 这里填写要修改的Excel文件的绝对路径
workbook = excel.Workbooks.Open(r"d:\tmp\income1.xlsx")
# 得到 2017 表单
sheet = workbook.Sheets('2017')
# 修改表单第一行第一列单元格内容
# com接口,单元格行号、列号从1开始
sheet.Cells(1,1).Value="你好"
# 保存内容
workbook.Save()
# 关闭该Excel文件
workbook.Close()
# excel进程退出
excel.Quit()
# 释放相关资源
sheet = None
book = None
excel.Quit()
excel = None
运行一下可以发现Excel内容也能修改。
关于使用com接口操作Excel具体细节, 可以点击这里,参考微软官方文档
COM 接口、xlrd库 打开数据文件 和 读取数据的性能对比,大家可以参考下面这段代码。
import time
def byCom():
t1 = time.time()
import win32com.client
excel = win32com.client.Dispatch("Excel.Application")
# excel.Visible = True # 可以让excel 可见
workbook = excel.Workbooks.Open(r"h:\tmp\ruijia\数据.xlsx")
sheet = workbook.Sheets(2)
print(sheet.Cells(2,15).Value)
print(sheet.UsedRange.Rows.Count) #多少行
t2 = time.time()
print(f'打开: 耗时{t2 - t1}秒')
total = 0
for row in range(2,sheet.UsedRange.Rows.Count+1):
value = sheet.Cells(row,15).Value
if type(value) not in [int,float]:
continue
total += value
print(total)
t3 = time.time()
print(f'读取数据: 耗时{t3 - t2}秒')
def byXlrd():
t1 = time.time()
import xlrd
# 加载 excel 文件
srcBook = xlrd.open_workbook("数据.xlsx")
sheet = srcBook.sheet_by_index(1)
print(sheet.cell_value(rowx=1,colx=14))
print(sheet.nrows) #多少行
t2 = time.time()
print(f'打开: 耗时{t2 - t1}秒')
total = 0
for row in range(1,sheet.nrows):
value = sheet.cell_value(row, 14)
if type(value) == str:
continue
total += value
print(total)
t3 = time.time()
print(f'读取数据: 耗时{t3 - t2}秒')
byCom()
byXlrd()