本篇内容介绍了“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:codePojectslogStatistics
esult
esult.xlsx')读取现有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:codePojectslogStatistics
esult
esult.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:codePojectslogStatistics
esult
esult%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')实践发现,多线程的情况下,使用
DispatchDispatch以上就是Python基于win32com客户端怎么实现Excel操作的详细内容,更多关于Python基于win32com客户端怎么实现Excel操作的资料请关注九品源码其它相关文章!