測驗環境
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 = https://www.cnblogs.com/shouke/archive/2023/04/29/目標值 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 = https://www.cnblogs.com/shouke/archive/2023/04/29/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
作者:授客
微信/QQ:1033553122
全國軟體測驗QQ交流群:7156436
Git地址:https://gitee.com/ishouke
友情提示:限于時間倉促,文中可能存在錯誤,歡迎指正、評論!
作者五行缺錢,如果覺得文章對您有幫助,請掃描下邊的二維碼打賞作者,金額隨意,您的支持將是我繼續創作的源動力,打賞后如有任何疑問,請聯系我!!!
微信打賞
支付寶打賞 全國軟體測驗交流QQ群
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/551487.html
標籤:其他
上一篇:FFmpeg開發筆記(二)搭建Windows系統的開發環境
下一篇:返回列表