Python มีโมดูล openpyxl สำหรับจัดการไฟล์ Excel (.xlsx) สร้าง อ่าน เขียน จัดการ sheet ได้
การติดตั้ง
pip install openpyxl
1. สร้าง Workbook และตั้งชื่อ Sheet
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active
print("Default sheet title:", sheet.title) # Sheet
# เปลี่ยนชื่อ sheet
sheet.title = "My New Sheet"
print("New sheet name:", sheet.title)
wb.save("Book1.xlsx")
2. เขียนข้อมูลลง Cell
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active
# วิธีที่ 1: ใช้ cell(row, column)
c1 = sheet.cell(row=1, column=1)
c1.value = "Aadrika"
c2 = sheet.cell(row=1, column=2)
c2.value = "Adwaita"
# วิธีที่ 2: ใช้ A1 notation
sheet['A2'] = "Satyajit"
sheet['B2'] = "Bivas"
wb.save("Book1.xlsx")
ผลลัพธ์

3. เพิ่ม Sheet ใหม่
wb = openpyxl.Workbook()
wb.create_sheet(index=1, title="New Sheet")
wb.save("Book1.xlsx")

4. อ่านข้อมูลจาก Excel
import openpyxl
path = "Book1.xlsx"
wb = openpyxl.load_workbook(path)
sheet = wb.active
# จำนวนแถวและคอลัมน์
print("Max row:", sheet.max_row) # 2
print("Max column:", sheet.max_column) # 2
# อ่านเซลล์เฉพาะ
print("A1:", sheet.cell(row=1, column=1).value) # Aadrika
print("B2:", sheet['B2'].value) # Bivas
# อ่านหัวคอลัมน์ (Row 1)
for i in range(1, sheet.max_column + 1):
print(sheet.cell(row=1, column=i).value, end=" ")
# Aadrika Adwaita
print()
# อ่านคอลัมน์แรก (Column A)
for i in range(1, sheet.max_row + 1):
print(sheet.cell(row=i, column=1).value)
# Aadrika
# Satyajit
# อ่านแถวที่ 2 ทั้งหมด
for i in range(1, sheet.max_column + 1):
print(sheet.cell(row=2, column=i).value, end=" ")
# Satyajit Bivas
5. วนลูปอ่านทั้ง Sheet (Iterate Rows)
# อ่านทุกเซลล์
for row in sheet.iter_rows(values_only=True):
print(row)
# ('Aadrika', 'Adwaita')
# ('Satyajit', 'Bivas')
# หรือใช้ iter_rows แบบมี coordinate
for row in sheet.iter_rows(min_row=1, max_row=2, min_col=1, max_col=2):
for cell in row:
print(f"{cell.coordinate}: {cell.value}")
6. สูตร (Formulas) และสไตล์ (Styling)
from openpyxl.styles import Font, Alignment, PatternFill
sheet['A3'] = 'Total'
sheet['B3'] = '=SUM(B1:B2)' # สูตร Excel
# จัดรูปแบบ
sheet['A1'].font = Font(bold=True, size=14)
sheet['A1'].fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
sheet['A1'].alignment = Alignment(horizontal="center")
wb.save("Book1.xlsx")
สรุป: openpyxl เป็นไลบรารีครบครันสำหรับ .xlsx รองรับสูตร สไตล์ กราฟ Pivot tables ฯลฯ