Python 基于win32com客戶(hù)端實(shí)現(xiàn)Excel操作的詳細(xì)過(guò)程
測(cè)試環(huán)境
Python 3.6.2
代碼實(shí)現(xiàn)
非多線程場(chǎng)景下使用
新建并保存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)程界面是否可見(jiàn) False表示后臺(tái)運(yùn)行
excel_app.DisplayAlerts = False # 設(shè)置是否顯示警告和消息框
book = excel_app.Workbooks.Add() # 添加Excel工作簿
sheet = excel_app.Worksheets(1) # 獲取第一個(gè)Sheet
sheet.name = '匯總統(tǒng)計(jì)' # 設(shè)置Sheet名稱(chēng)
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(['日期', '請(qǐng)求方法', '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è)置字體名稱(chēng)
# sheet.Cells(2, 2).Font.Color = RGB(0, 0, 255) # 設(shè)置字體顏色 # 不起作用
sheet2 = excel_app.Worksheets.Add() # 添加Sheet頁(yè)
sheet2.Activate # 設(shè)置默認(rèn)選中的sheet為sheet2
sheet3 = excel_app.Worksheets.Add()
#注意,Move操作,會(huì)將被移動(dòng)的表單(本例中的sheet)設(shè)置為默認(rèn)選中狀態(tài),也就是說(shuō)覆蓋 sheet.Activate所做的變更
sheet.Move(sheet3, None) # 將sheet移動(dòng)到sheet3之前
book.SaveAs(result_file_path) # 注意:結(jié)果文件路徑必須是絕對(duì)路徑
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) # 打開(kāi)工作簿
# do something ...
sheet = excel_app.Worksheets(1)
print(sheet.name)
print(sheet.Cells(1, 1).Value)
book.SaveAs(result_file_path) # 注意:結(jié)果文件路徑必須是絕對(duì)路徑
book.Close() # 關(guān)閉工作簿
excel_app.Quit() # 退出
if __name__ == '__main__':
read_something_from_excel('D:\\codePojects\\logStatistics\\result\\result.xlsx')多線程場(chǎng)景下使用
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)計(jì)'
row_index = 1
for index, item in enumerate(['日期', '請(qǐng)求方法', '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()說(shuō)明:
- 如果不添加以下代碼行:
pythoncom.CoInitialize()
會(huì)報(bào)錯(cuò),如下:
pywintypes.com_error: (-2147221008, '尚未調(diào)用 CoInitialize。', None, None)
- 建議使用
excel_app = win32com.client.DispatchEx('Excel.Application')替代
# excel_app = win32com.client.Dispatch('Excel.Application')實(shí)踐發(fā)現(xiàn),多線程的情況下,使用Dispatch會(huì)出現(xiàn)報(bào)錯(cuò),原因似乎是Dispatch若發(fā)現(xiàn)進(jìn)程已經(jīng)存在的話,就不會(huì)創(chuàng)建新的進(jìn)程。若不創(chuàng)建新的進(jìn)程,有些操作會(huì)有沖突,可能會(huì)影響到已經(jīng)打開(kāi)的文件。
參考連接
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客戶(hù)端實(shí)現(xiàn)Excel操作的詳細(xì)過(guò)程的文章就介紹到這了,更多相關(guān)Python Excel操作內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python如何操作office實(shí)現(xiàn)自動(dòng)化及win32com.client的運(yùn)用
- 解決python中導(dǎo)入win32com.client出錯(cuò)的問(wèn)題
- Python操作word常見(jiàn)方法示例【win32com與docx模塊】
- Python使用win32com模塊實(shí)現(xiàn)數(shù)據(jù)庫(kù)表結(jié)構(gòu)自動(dòng)生成word表格的方法
- Python使用win32com實(shí)現(xiàn)的模擬瀏覽器功能示例
- Python win32com 操作Exce的l簡(jiǎn)單方法(必看)
- python使用win32com庫(kù)播放mp3文件的方法
- python字符串加密解密的三種方法分享(base64 win32com)
相關(guān)文章
Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫(kù)的方法示例
這篇文章主要介紹了Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫(kù)的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
python基于Kivy寫(xiě)一個(gè)圖形桌面時(shí)鐘程序
這篇文章主要介紹了python如何基于Kivy 寫(xiě)一個(gè)桌面時(shí)鐘程序,幫助大家更好的利用python開(kāi)發(fā)圖形程序,感興趣的朋友可以了解下2021-01-01
python簡(jiǎn)單實(shí)現(xiàn)計(jì)算過(guò)期時(shí)間的方法
這篇文章主要介紹了python簡(jiǎn)單實(shí)現(xiàn)計(jì)算過(guò)期時(shí)間的方法,涉及Python時(shí)間操作的相關(guān)技巧,需要的朋友可以參考下2015-06-06

