Python 基于win32com客戶端實現(xiàn)Excel操作的詳細(xì)過程
測試環(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è)置進(jìn)程界面是否可見 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ìn)程已經(jīng)存在的話,就不會創(chuàng)建新的進(jìn)程。若不創(chuàng)建新的進(jìn)程,有些操作會有沖突,可能會影響到已經(jīng)打開的文件。
參考連接
https://learn.microsoft.com/zh-cn/office/vba/api/excel.font.color
https://blog.csdn.net/qq_25176745/article/details/125085819
到此這篇關(guān)于Python 基于win32com客戶端實現(xiàn)Excel操作的詳細(xì)過程的文章就介紹到這了,更多相關(guān)Python Excel操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python如何操作office實現(xiàn)自動化及win32com.client的運用
- 解決python中導(dǎo)入win32com.client出錯的問題
- Python操作word常見方法示例【win32com與docx模塊】
- Python使用win32com模塊實現(xiàn)數(shù)據(jù)庫表結(jié)構(gòu)自動生成word表格的方法
- Python使用win32com實現(xiàn)的模擬瀏覽器功能示例
- Python win32com 操作Exce的l簡單方法(必看)
- python使用win32com庫播放mp3文件的方法
- python字符串加密解密的三種方法分享(base64 win32com)
相關(guān)文章
Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫的方法示例
這篇文章主要介紹了Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫的方法示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03