Python 基于win32com客户端实现Excel操作的详细过程

后端开发   发布日期:2023年05月29日   浏览次数:46

测试环境

Python 3.6.2

代码实现

非多线程场景下使用

新建并保存EXCEL

  1. import win32com.client
  2. from win32api import RGB
  3. def save_something_to_excel(result_file_path):
  4. excel_app = win32com.client.Dispatch('Excel.Application')
  5. excel_app.Visible = False # 设置进程界面是否可见 False表示后台运行
  6. excel_app.DisplayAlerts = False # 设置是否显示警告和消息框
  7. book = excel_app.Workbooks.Add() # 添加Excel工作簿
  8. sheet = excel_app.Worksheets(1) # 获取第一个Sheet
  9. sheet.name = '汇总统计' # 设置Sheet名称
  10. sheet.Columns.ColumnWidth = 10 # 设置所有列列宽
  11. sheet.Columns(1).ColumnWidth = 20 # 设置第1列列宽
  12. sheet.Rows.RowHeight = 15 # 设置所有行高
  13. sheet.Rows(1).RowHeight = 20 # 设置第一行行高
  14. usedRange = sheet.UsedRange # 获取sheet的已使用范围
  15. rows = usedRange.Rows.Count # 获取已使用范围的最大行数,初始值为 1
  16. cols = usedRange.Columns.Count # 获取已使用范围的最大列数,初始值为 1
  17. print(rows, cols) # 输出 1 1
  18. usedRange.Rows.RowHeight = 30 # 设置已使用范围内的行高
  19. usedRange.Columns.ColumnWidth = 30 # 设置已使用范围内的列宽
  20. # do something ...
  21. row_index = 1
  22. for index, item in enumerate(['日期', '请求方法', 'URL', '调用次数']):
  23. # 单元格赋值 sheet.Cells(row_index, col_index).Value = 目标值 row_index, col_index 起始值为1
  24. sheet.Cells(row_index, index + 1).Value = item
  25. row_index += 1
  26. # do something else ...
  27. usedRange = sheet.UsedRange
  28. rows = usedRange.Rows.Count
  29. cols = usedRange.Columns.Count
  30. print(rows, cols) # 输出 1 4
  31. sheet.Cells(1, 2).Font.Size = 29 # 设置单元格字体大小
  32. sheet.Cells(1, 2).Font.Bold = True # 字体是否加粗 True 表示加粗,False 表示不加粗
  33. sheet.Cells(2, 2).Font.Name = "微软雅黑" # 设置字体名称
  34. # sheet.Cells(2, 2).Font.Color = RGB(0, 0, 255) # 设置字体颜色 # 不起作用
  35. sheet2 = excel_app.Worksheets.Add() # 添加Sheet页
  36. sheet2.Activate # 设置默认选中的sheet为sheet2
  37. sheet3 = excel_app.Worksheets.Add()
  38. #注意,Move操作,会将被移动的表单(本例中的sheet)设置为默认选中状态,也就是说覆盖 sheet.Activate所做的变更
  39. sheet.Move(sheet3, None) # 将sheet移动到sheet3之前
  40. book.SaveAs(result_file_path) # 注意:结果文件路径必须是绝对路径
  41. book.Close() # 关闭工作簿
  42. excel_app.Quit() # 退出
  43. if __name__ == '__main__':
  44. save_something_to_excel('D:\\codePojects\\logStatistics\\result\\result.xlsx')

了解更多API,可以查看参考连接

读取现有EXCEL

  1. import win32com.client
  2. def read_something_from_excel(excel_file_path):
  3. excel_app = win32com.client.Dispatch('Excel.Application')
  4. excel_app.Visible = False
  5. excel_app.DisplayAlerts = False
  6. book = excel_app.Workbooks.Open(result_file_path, False, True, None, None) # 打开工作簿
  7. # do something ...
  8. sheet = excel_app.Worksheets(1)
  9. print(sheet.name)
  10. print(sheet.Cells(1, 1).Value)
  11. book.SaveAs(result_file_path) # 注意:结果文件路径必须是绝对路径
  12. book.Close() # 关闭工作簿
  13. excel_app.Quit() # 退出
  14. if __name__ == '__main__':
  15. read_something_from_excel('D:\\codePojects\\logStatistics\\result\\result.xlsx')

多线程场景下使用

  1. import threading
  2. import win32com.client
  3. import pythoncom
  4. def save_something_to_excel(result_file_path):
  5. pythoncom.CoInitialize()
  6. excel_app = win32com.client.DispatchEx('Excel.Application')
  7. # excel_app = win32com.client.Dispatch('Excel.Application')
  8. excel_app.Visible = False
  9. excel_app.DisplayAlerts = False
  10. book = excel_app.Workbooks.Add()
  11. sheet = excel_app.Worksheets(1)
  12. sheet.name = '汇总统计'
  13. row_index = 1
  14. for index, item in enumerate(['日期', '请求方法', 'URL', '调用次数']):
  15. sheet.Cells(row_index, index + 1).Value = item
  16. row_index += 1
  17. book.SaveAs(result_file_path)
  18. book.Close()
  19. excel_app.Quit()
  20. pythoncom.CoUninitialize() # 释放资源
  21. if __name__ == '__main__':
  22. for i in range(3):
  23. file_path = 'D:\\codePojects\\logStatistics\\result\\result%s.xlsx' % i
  24. thread = threading.Thread(target=save_something_to_excel,
  25. args=(file_path,))
  26. 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')

实践发现,多线程的情况下,使用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操作的详细过程的详细内容,更多关于Python 基于win32com客户端实现Excel操作的详细过程的资料请关注九品源码其它相关文章!