Try   HackMD

Python 教學 | openpyxl 自動寫入資料到 excel

之前家教的學生說想學用 python 寫入資料到 excel,這個實用技巧不分享不行,所以就有這篇文章啦!這次使用的套件 openpyxl 這個模組,程式碼和操作都很簡單直觀。

安裝套件

$ pip install openpyxl

一點點名詞介紹

稍微記一下,等一下比較不會搞混。
workbook : 活頁簿
sheet : 分頁
cell(row,col) : 資料儲存格,row為第幾列,col為第幾行

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

開啟、儲存檔案

建立新檔 : workbook = openpyxl.Workbook()
開啟舊檔 : workbook = openpyxl.load_workbook("檔名")
儲存檔案 : workbook.save("檔名")

分頁相關

取得分頁 : sheet = workbook.worksheets[0]sheet = workbook["分頁名"]

建立分頁 : sheet = workbook.create_sheet("分頁名")
命名分頁 : sheet.title = "分頁名"

資料儲存格相關

取得資料儲存格 : sheet.cell(row,col)sheet['A1']

寫入資料 : sheet.cell(row,col).value="Hello"sheet['A1'].value="Hello"
在資料儲存格後加上.value就可以啦,這邊要注意row和col都是從1開始算,不是從0喔~

程式碼 Demo

import openpyxl
workbook = openpyxl.Workbook() # 建立新的活頁簿
sheet = workbook.worksheets[0] # 取得第一個分頁
sheet.title = "fruit"          # 重新命名分頁

# 寫入資料
sheet.cell(1,1).value = "apple"
sheet.cell(2,1).value = "banana"
sheet.cell(3,1).value = "cherry"
sheet["B1"].value = 30
sheet["B2"].value = 10
sheet["B3"].value = 60
sheet["B4"].value = "=SUM(B1:B3)" # 也可以寫入數學公式

workbook.save("test.xlsx") # 記得存檔,不然就是做白工喔

成果如下

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

當然 openpyxl 還有很多種使用方法,今天就先介紹這幾個最實用的~
我的部落格還有其他文章,歡迎大家來逛逛呦~