Python 基于win32com客户端实现Excel操作的详细过程
作者:授客 时间:2021-01-18 11:22:47
测试环境
Python 3.6.2
代码实现
非多线程场景下使用
新建并保存EXCEL
import win32com.client
from win32api import RGB
def save_something_to_excel(result_file_path):
excel_app = win32com.client.Dispatch('Excel.Application')
excel_app.Visible = False # 设置进程界面是否可见 False表示后台运行
excel_app.DisplayAlerts = False # 设置是否显示警告和消息框
book = excel_app.Workbooks.Add() # 添加Excel工作簿
sheet = excel_app.Worksheets(1) # 获取第一个Sheet
sheet.name = '汇总统计' # 设置Sheet名称
sheet.Columns.ColumnWidth = 10 # 设置所有列列宽
sheet.Columns(1).ColumnWidth = 20 # 设置第1列列宽
sheet.Rows.RowHeight = 15 # 设置所有行高
sheet.Rows(1).RowHeight = 20 # 设置第一行行高
usedRange = sheet.UsedRange # 获取sheet的已使用范围
rows = usedRange.Rows.Count # 获取已使用范围的最大行数,初始值为 1
cols = usedRange.Columns.Count # 获取已使用范围的最大列数,初始值为 1
print(rows, cols) # 输出 1 1
usedRange.Rows.RowHeight = 30 # 设置已使用范围内的行高
usedRange.Columns.ColumnWidth = 30 # 设置已使用范围内的列宽
# do something ...
row_index = 1
for index, item in enumerate(['日期', '请求方法', 'URL', '调用次数']):
# 单元格赋值 sheet.Cells(row_index, col_index).Value = 目标值 row_index, col_index 起始值为1
sheet.Cells(row_index, index + 1).Value = item
row_index += 1
# do something else ...
usedRange = sheet.UsedRange
rows = usedRange.Rows.Count
cols = usedRange.Columns.Count
print(rows, cols) # 输出 1 4
sheet.Cells(1, 2).Font.Size = 29 # 设置单元格字体大小
sheet.Cells(1, 2).Font.Bold = True # 字体是否加粗 True 表示加粗,False 表示不加粗
sheet.Cells(2, 2).Font.Name = "微软雅黑" # 设置字体名称
# sheet.Cells(2, 2).Font.Color = RGB(0, 0, 255) # 设置字体颜色 # 不起作用
sheet2 = excel_app.Worksheets.Add() # 添加Sheet页
sheet2.Activate # 设置默认选中的sheet为sheet2
sheet3 = excel_app.Worksheets.Add()
#注意,Move操作,会将被移动的表单(本例中的sheet)设置为默认选中状态,也就是说覆盖 sheet.Activate所做的变更
sheet.Move(sheet3, None) # 将sheet移动到sheet3之前
book.SaveAs(result_file_path) # 注意:结果文件路径必须是绝对路径
book.Close() # 关闭工作簿
excel_app.Quit() # 退出
if __name__ == '__main__':
save_something_to_excel('D:\\codePojects\\logStatistics\\result\\result.xlsx')
了解更多API,可以查看参考连接
读取现有EXCEL
import win32com.client
def read_something_from_excel(excel_file_path):
excel_app = win32com.client.Dispatch('Excel.Application')
excel_app.Visible = False
excel_app.DisplayAlerts = False
book = excel_app.Workbooks.Open(result_file_path, False, True, None, None) # 打开工作簿
# do something ...
sheet = excel_app.Worksheets(1)
print(sheet.name)
print(sheet.Cells(1, 1).Value)
book.SaveAs(result_file_path) # 注意:结果文件路径必须是绝对路径
book.Close() # 关闭工作簿
excel_app.Quit() # 退出
if __name__ == '__main__':
read_something_from_excel('D:\\codePojects\\logStatistics\\result\\result.xlsx')
多线程场景下使用
import threading
import win32com.client
import pythoncom
def save_something_to_excel(result_file_path):
pythoncom.CoInitialize()
excel_app = win32com.client.DispatchEx('Excel.Application')
# excel_app = win32com.client.Dispatch('Excel.Application')
excel_app.Visible = False
excel_app.DisplayAlerts = False
book = excel_app.Workbooks.Add()
sheet = excel_app.Worksheets(1)
sheet.name = '汇总统计'
row_index = 1
for index, item in enumerate(['日期', '请求方法', 'URL', '调用次数']):
sheet.Cells(row_index, index + 1).Value = item
row_index += 1
book.SaveAs(result_file_path)
book.Close()
excel_app.Quit()
pythoncom.CoUninitialize() # 释放资源
if __name__ == '__main__':
for i in range(3):
file_path = 'D:\\codePojects\\logStatistics\\result\\result%s.xlsx' % i
thread = threading.Thread(target=save_something_to_excel,
args=(file_path,))
thread.start()
说明:
如果不添加以下代码行:
pythoncom.CoInitialize()
会报错,如下:
pywintypes.com_error: (-2147221008, '尚未调用 CoInitialize。', None, None)
建议使用
excel_app = win32com.client.DispatchEx('Excel.Application')
替代
# excel_app = win32com.client.Dispatch('Excel.Application')
实践发现,多线程的情况下,使用Dispatch
会出现报错,原因似乎是Dispatch
若发现进程已经存在的话,就不会创建新的进程。若不创建新的进程,有些操作会有冲突,可能会影响到已经打开的文件。
参考连接
https://learn.microsoft.com/zh-cn/office/vba/api/excel.font.color
https://blog.csdn.net/qq_25176745/article/details/125085819
来源:https://www.cnblogs.com/shouke/archive/2023/04/29/17277611.html
标签:Python,win32com,Excel
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
ASP 3.0中的新特性
2008-02-27 13:28:00
![](https://img.aspxhome.com/file/UploadPic/20082/27/2008227134234597s.jpg)
python中get和post有什么区别
2022-04-17 16:45:15
Oracle 数据表分区的策略
2023-07-08 12:19:18
ORACLE常见错误代码的分析与解决三
2010-07-26 13:28:00
经典分享MySQL的limit查询优化
2011-05-05 15:47:00
详细讲解删除SQL Server日志的具体方法
2008-12-09 14:32:00
Python实现根据日期获取当天凌晨时间戳的方法示例
2023-08-04 14:16:46
javaScript通用数据类型校验函数
2009-07-06 12:49:00
利用python程序生成word和PDF文档的方法
2023-08-26 13:31:44
三个动画函数,透明度渐变、位置移动、尺寸变化javascript源码
2010-03-28 13:23:00
管理员必读10个重要MySQL客户启动选项
2008-06-07 16:57:00
![](https://img.aspxhome.com/file/UploadPic/20086/7/200867171031126s.jpg)
编写python代码实现简单抽奖器
2023-04-07 12:32:48
![](https://img.aspxhome.com/file/2023/8/71398_0s.jpg)
一个取图片尺寸的类,支持jpg,gif,png
2007-10-18 10:25:00
实例讲解MySQL数据库中文问题的解决方法
2008-12-31 15:15:00
解决django无法访问本地static文件(js,css,img)网页里js,cs都加载不了
2023-06-13 19:13:36
![](https://img.aspxhome.com/file/2023/7/59637_0s.jpg)
大家都对vertical-align的各说各话
2008-06-19 12:11:00
![](https://img.aspxhome.com/file/UploadPic/20086/19/2008619121517533s.gif)
MySQL与PHP的基础与应用专题之数据控制
2023-11-23 01:03:21
![](https://img.aspxhome.com/file/2023/8/99348_0s.png)
asp.net php asp jsp 301重定向的代码(集合)
2023-11-14 15:02:06
SQL中exists的使用方法
2011-12-01 08:36:07
Oracle SQL性能优化系列学习二
2010-07-23 13:23:00