Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การอ่านและเขียนไฟล์ Excel ด้วย openpyxl ใน Python

บทนำ

openpyxl เป็น library สำหรับอ่าน/เขียนไฟล์ Excel 2010+ (.xlsx, .xlsm, .xltx, .xltm) ไม่รองรับ .xls เก่า

การติดตั้ง

pip install openpyxl

การ Import

from openpyxl import Workbook
import openpyxl

สร้างและบันทึกไฟล์ Excel

wb = Workbook()
sheet = wb.active
sheet['A1'] = "Hello"
sheet['A2'] = "World!"
sheet['A3'] = 41.80
sheet['A4'] = 10
# หรือใช้ cell coordinates
sheet.cell(row=2, column=2).value = 5  # B2 = 5
wb.save("example.xlsx")

อ่านข้อมูลจากไฟล์ Excel

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)
# Output: Hello World! 41.8 10

โค้ดตัวอย่างครบถ้วน

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)

คำอธิบาย

  • Workbook = ไฟล์ Excel ทั้งเล่ม (มีหลาย Sheets)
  • Sheet = แผ่นงาน (Rows 1..N, Columns A..Z, AA..)
  • เข้าถึง cell: sheet['A1'] หรือ sheet.cell(row, column)
  • ค่าอยู่ที่ attribute .value

คุณสมบัติเพิ่มเติม

openpyxl รองรับ: formulas, charts, styles, conditional formatting, merged cells, images, data validation ฯลฯ

เอกสาร: https://pypi.org/project/openpyxl/