它相当于一个桥梁,连接python语言和c语言。其他操作excel的模块也很多,比如xlwt、xwings。但是win32com功能更强大,可以操作word、调用宏等等等。
python2这个模块是pywin32里的,python3我找了很久发现是pypiwin32。 首先假设你的D盘里有个hel.xlsm的excel文件,后缀xlsm含义是改文件里带宏,假设这个宏名叫“每日操作”。至于宏这些东西是一套c语言基础的程序,可以用来代替手动操作excel。具体以后可能会更新。
#!/usr/bin/env python
# -*- coding: utf-
8 -*-
import win32com
from win32com.client
import Dispatch, constants
填入数据
def excel_open(file_path,results,sheet_name):
xlApp = win32com.client.DispatchEx(
"Excel.Application")
xlApp.Visible =
True
xlApp.DisplayAlerts =
0
xlBook = xlApp.Workbooks.Open(file_path,
False)
sht = xlBook.Worksheets(sheet_name)
for i
in range(len(results)):
for j
in range(len(results[
0])):
sht.Cells(i +
2, j +
1).Value =results[i][j]
print(
"WRITE FINISHED")
xlBook.Close(
True)
xlApp.quit()
运行宏
def useVBA(VBA):
xlApp = win32com.client.DispatchEx(
"Excel.Application")
xlApp.Visible =
True
xlApp.DisplayAlerts =
0
xlBook = xlApp.Workbooks.Open(file_path,
False)
xlBook.Application.Run(VBA)
xlBook.Close(
True)
xlApp.quit()
操作
results=((
5,
2,
1),(
7,
2,
7),(
4,
0,
3))
file_path=
"D:\hel.xlsm"
sheet_name=
"我还在想"
VBA=
"每日操作"
excel_open(file_path,results,sheet_name)
useVBA(VBA)