測試環(huán)境
Python 3.6.2
代碼實現(xiàn)
非多線程場景下使用
新建并保存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 # 設(shè)置進程界面是否可見 False表示后臺運行
excel_app.DisplayAlerts = False # 設(shè)置是否顯示警告和消息框
book = excel_app.Workbooks.Add() # 添加Excel工作簿
sheet = excel_app.Worksheets(1) # 獲取第一個Sheet
sheet.name = '匯總統(tǒng)計' # 設(shè)置Sheet名稱
sheet.Columns.ColumnWidth = 10 # 設(shè)置所有列列寬
sheet.Columns(1).ColumnWidth = 20 # 設(shè)置第1列列寬
sheet.Rows.RowHeight = 15 # 設(shè)置所有行高
sheet.Rows(1).RowHeight = 20 # 設(shè)置第一行行高
usedRange = sheet.UsedRange # 獲取sheet的已使用范圍
rows = usedRange.Rows.Count # 獲取已使用范圍的最大行數(shù),初始值為 1
cols = usedRange.Columns.Count # 獲取已使用范圍的最大列數(shù),初始值為 1
print(rows, cols) # 輸出 1 1
usedRange.Rows.RowHeight = 30 # 設(shè)置已使用范圍內(nèi)的行高
usedRange.Columns.ColumnWidth = 30 # 設(shè)置已使用范圍內(nèi)的列寬
# do something ...
row_index = 1
for index, item in enumerate(['日期', '請求方法', 'URL', '調(diào)用次數(shù)']):
# 單元格賦值 sheet.Cells(row_index, col_index).Value = 目標(biāo)值 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 # 設(shè)置單元格字體大小
sheet.Cells(1, 2).Font.Bold = True # 字體是否加粗 True 表示加粗,F(xiàn)alse 表示不加粗
sheet.Cells(2, 2).Font.Name = "微軟雅黑" # 設(shè)置字體名稱
# sheet.Cells(2, 2).Font.Color = RGB(0, 0, 255) # 設(shè)置字體顏色 # 不起作用
sheet2 = excel_app.Worksheets.Add() # 添加Sheet頁
sheet2.Activate # 設(shè)置默認(rèn)選中的sheet為sheet2
sheet3 = excel_app.Worksheets.Add()
#注意,Move操作,會將被移動的表單(本例中的sheet)設(shè)置為默認(rèn)選中狀態(tài),也就是說覆蓋 sheet.Activate所做的變更
sheet.Move(sheet3, None) # 將sheet移動到sheet3之前
book.SaveAs(result_file_path) # 注意:結(jié)果文件路徑必須是絕對路徑
book.Close() # 關(guān)閉工作簿
excel_app.Quit() # 退出
if __name__ == '__main__':
save_something_to_excel('D:\\codePojects\\logStatistics\\result\\result.xlsx')
了解更多API,可以查看參考連接
讀取現(xiàn)有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) # 注意:結(jié)果文件路徑必須是絕對路徑
book.Close() # 關(guān)閉工作簿
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 = '匯總統(tǒng)計'
row_index = 1
for index, item in enumerate(['日期', '請求方法', 'URL', '調(diào)用次數(shù)']):
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, '尚未調(diào)用 CoInitialize。', None, None)
-
建議使用
excel_app = win32com.client.DispatchEx('Excel.Application')
替代
# excel_app = win32com.client.Dispatch('Excel.Application')
實踐發(fā)現(xiàn),多線程的情況下,使用
Dispatch
會出現(xiàn)報錯,原因似乎是Dispatch
若發(fā)現(xiàn)進程已經(jīng)存在的話,就不會創(chuàng)建新的進程。若不創(chuàng)建新的進程,有些操作會有沖突,可能會影響到已經(jīng)打開的文件。
參考連接
https://learn.microsoft.com/zh-cn/office/vba/api/excel.font.color文章來源:http://www.zghlxwxcb.cn/news/detail-428942.html
https://blog.csdn.net/qq_25176745/article/details/125085819文章來源地址http://www.zghlxwxcb.cn/news/detail-428942.html
到了這里,關(guān)于Python 基于win32com客戶端實現(xiàn)Excel操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!