Python 基于win32com客户端实现Excel操作

简介: Python 基于win32com客户端实现Excel操作

测试环境

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()

说明:

  1. 如果不添加以下代码行:
pythoncom.CoInitialize()
  1. 会报错,如下:
pywintypes.com_error: (-2147221008, '尚未调用 CoInitialize。', None, None)
  1. 建议使用
excel_app = win32com.client.DispatchEx('Excel.Application')
  1. 替代
# excel_app = win32com.client.Dispatch('Excel.Application')
  1. 实践发现,多线程的情况下,使用Dispatch会出现报错,原因似乎是Dispatch若发现进程已经存在的话,就不会创建新的进程。若不创建新的进程,有些操作会有冲突,可能会影响到已经打开的文件。

参考连接

https://learn.microsoft.com/zh-cn/office/vba/api/excel.font.color

https://blog.csdn.net/qq_25176745/article/details/125085819

目录
相关文章
|
6天前
|
数据格式 Python
【Python】已解决:Excel无法打开文件test.xIsx“,因为文件格式或文件扩展名无效。请确定文件未损坏,并且文件扩展名与文件的格式匹配。
【Python】已解决:Excel无法打开文件test.xIsx“,因为文件格式或文件扩展名无效。请确定文件未损坏,并且文件扩展名与文件的格式匹配。
34 0
|
6天前
|
传感器 数据采集 算法
python实现ModBusRTU客户端方式
python实现基于串口通信的ModBusRTU客户端是一件简单的事情,只要通过pymodbus模块就可以实现。
|
2天前
|
数据格式 Python
Python代码示例,读取excel表格,将行数据转为列数据。(10)
【7月更文挑战第10天】Python代码示例,读取excel表格,将行数据转为列数据。
16 2
|
1天前
|
存储 对象存储 Python
`openpyxl`是一个用于读写Excel 2010 xlsx/xlsm/xltx/xltm文件的Python库。它不需要Microsoft Excel,也不需要.NET或COM组件。
`openpyxl`是一个用于读写Excel 2010 xlsx/xlsm/xltx/xltm文件的Python库。它不需要Microsoft Excel,也不需要.NET或COM组件。
6 1
|
3天前
|
Python
|
3天前
|
机器学习/深度学习 存储 数据可视化
这份Excel+Python飞速搞定数据分析手册,简直可以让Excel飞起来
微软在 UserVoice 上运营着⼀个反馈论坛,每个⼈都可以在这⾥提交新点⼦供他⼈投票。票数最⾼的功能请求是“将 Python 作为Excel 的⼀门脚本语⾔”,其得票数差不多是第⼆名的两倍。尽管⾃2015 年这个点⼦发布以来并没有什么实质性进展,但在 2020 年年末,Python 之⽗ Guido van Rossum 发布推⽂称“退休太无聊了”,他将会加入微软。此事令 Excel ⽤户重燃希望。我不知道他的举动是否影响了 Excel 和 Python 的集成,但我清楚的是,为何⼈们迫切需要结合 Excel 和 Python 的⼒量,⽽你⼜应当如何从今天开始将两者结合起来。总之,这就是本
|
4天前
|
数据可视化 数据挖掘 数据处理
Python对Excel两列数据进行运算【从基础到高级的全面指南】
【7月更文挑战第6天】使用Python的`pandas`库处理Excel数据,涉及安装`pandas`和`openpyxl`,读取数据如`df = pd.read_excel('data.xlsx')`,进行运算如`df['Sum'] = df['Column1'] + df['Column2']`,并将结果写回Excel。`pandas`还支持数据筛选、分组、可视化、异常处理和性能优化。通过熟练运用这些功能,可以高效分析Excel表格。
9 0
|
6天前
|
开发者 Python
【Python】已解决:(pandas read_excel 读取Excel报错)ImportError: Pandas requires version ‘2.0.1’ or newer of ‘x
【Python】已解决:(pandas read_excel 读取Excel报错)ImportError: Pandas requires version ‘2.0.1’ or newer of ‘x
13 0
|
6天前
|
Python
【Python】已解决:(Python xlwt写入Excel样式报错)ValueError: More than 4094 XFs (styles)
【Python】已解决:(Python xlwt写入Excel样式报错)ValueError: More than 4094 XFs (styles)
9 0
|
6天前
|
Python
【Python】已解决:(Python xlwt写入Excel报错)AttributeError: ‘function’ object has no attribute ‘font’
【Python】已解决:(Python xlwt写入Excel报错)AttributeError: ‘function’ object has no attribute ‘font’
9 0