Giới thiệu
openpyxl là thư viện Python đọc/ghi file Excel 2010 (xlsx/xlsm/xltx/xltm). File Excel gọi là Workbook chứa ít nhất 1 Sheet. Sheet gồm hàng (bắt đầu 1) và cột (bắt đầu A).
Cài đặt
pip install openpyxl
Import
from openpyxl import Workbook
Tạo và lưu dữ liệu vào file Excel
wb = Workbook()
sheet = wb.active
sheet['A1'] = "Hello"
sheet['A2'] = "World!"
sheet['A3'] = 41.80
sheet['A4'] = 10
wb.save("example.xlsx")
Có thể dùng tọa độ ô: sheet.cell(row=2, column=2).value = 5 → ghi vào B2.
Đọc dữ liệu từ file Excel
import openpyxl
wb = openpyxl.load_workbook("example.xlsx")
sheet = wb.active
temp1 = sheet['A1']
temp2 = sheet['B1']
temp3 = sheet.cell(row=3, column=1)
temp4 = sheet.cell(row=4, column=1)
print(temp1.value, temp2.value, temp3.value, temp4.value)
Hello World! 41.8 10
Ví dụ hoàn chỉnh
from openpyxl import Workbook
import openpyxl
wb = Workbook()
sheet = wb.active
sheet['A1'] = "Hello"
sheet['B1'] = "World!"
sheet['A3'] = 41.80
sheet['A4'] = 10
wb.save("example.xlsx")
wb = openpyxl.load_workbook("example.xlsx")
sheet = wb.active
temp1 = sheet['A1']
temp2 = sheet['B1']
temp3 = sheet.cell(row=3, column=1)
temp4 = sheet.cell(row=4, column=1)
print(temp1.value, temp2.value, temp3.value, temp4.value)
Kết luận
Đã biết đọc/ghi Excel với Python. Thư viện còn hỗ trợ: thêm nhiều dữ liệu cùng lúc, vẽ biểu đồ, thống kê... Xem tài liệu chính thức.