Python

Python 使用 pywin32 模組操控 Excel 教學與範例

介紹如何使用 Python 的 pywin32 模組操控 Excel。

如果想在 Windows 中使用 Python 程式操控 Excel,可以使用 pywin32 這個 Python 模組,使用前先依照步驟安裝 pywin32 模組

新增 Excel 檔案

以下這個範例是使用 Python 操控 Excel,新增一個 Excel 活頁簿,並將資料寫入工作表,最後存檔離開。

import win32com.client

# 取得 Excel COMObject
excel = win32com.client.Dispatch('Excel.Application')

# 顯示視窗
excel.Visible = True

# 新增活頁簿
newBook = excel.Workbooks.Add()

# 取得目前的工作表
sheet = newBook.ActiveSheet

# 寫入資料
sheet.Cells(1, 1).Value = "Hello!"
sheet.Cells(1, 2).Value = "Excel."

# 儲存檔案
newBook.SaveAs("C:OfficeGuidedemo.xlsx")

# 關閉活頁簿
newBook.Close()

# 離開 Excel
excel.Application.Quit()

執行這段程式碼之後,就會建立一個檔名為 demo.xlsx 的 Excel 檔案。

Excel 檔案

編輯 Excel 檔案

以下是使用 Python 開啟上一個範例產生的 Excel 檔案,更改內容、文字顏色、字體的範例:

import win32com.client

# 取得 Excel COMObject
excel = win32com.client.Dispatch('Excel.Application')

# 顯示視窗
excel.Visible = True

# 開啟 Excel
myBook = excel.Workbooks.Open("C:OfficeGuidedemo.xlsx")

# 取得指定的工作表(可用索引或名稱)
sheet = myBook.Worksheets(1)
#sheet = myBook.Worksheets("我的工作表")

# 讀取資料
content = sheet.Cells(1, 1).Value
print(content)

# 寫入資料
sheet.Cells(2, 1).Value = "Edit by Python."

# 將文字設定為綠色
sheet.Cells(2, 1).Font.Color = 0x00FF00

# 將文字設定為粗體
sheet.Cells(2, 1).Font.Bold = True

# 設定文字字型
sheet.Cells(2, 1).Font.Name = "微軟雅黑"

# 儲存檔案
myBook.Save

# 關閉活頁簿
myBook.Close()

# 離開 Excel
excel.Application.Quit()

編輯之後的 Excel 檔案會像這樣:

Excel 檔案

參考資料:itread01子風的知識庫pythonlibrary

Share
Published by
Office Guide

Recent Posts

Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤

本篇介紹如何在 Python ...

9 個月 ago

Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例

本篇介紹如何在 Ubuntu ...

9 個月 ago

Linux 網路設定 ip 指令用法教學與範例

本篇介紹如何在 Linux 系...

9 個月 ago

Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例

本篇介紹如何在 Windows...

10 個月 ago

Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例

介紹如何在 Linux 中使用...

10 個月 ago

Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例

介紹如何在 Linux 系統中...

11 個月 ago