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

Python สำหรับผู้ใช้ Spreadsheet (Excel) - ไลบรารี openpyxl, xlwt, xlsxwriter

หลายไลบรารีสำหรับอ่าน/เขียน Excel ใน Python เลือกตามรุ่นไฟล์และฟีเจอร์ที่ต้องการ

1. openpyxl (สำหรับ .xlsx, .xlsm, .xltx, .xltm - Excel 2010+)

from openpyxl import Workbook
import datetime

wb = Workbook()
ws = wb.active

ws['A1'] = 50
ws.append([5, 15, 25, 35, 45, 55])
ws.append([9, 19, 29, 39, 49, 59])

now = datetime.datetime.now()
ws['A1'] = now.year
ws['A2'] = now

wb.save("openpyxl_output.xlsx")

2. xlwt (สำหรับ .xls - Excel 95-2003)

รองรับ formatting: font, color, bold, number format

import xlwt
from datetime import datetime

wb = xlwt.Workbook()
ws = wb.add_sheet('Sheet1')

style1 = xlwt.easyxf('font: name Times New Roman, color-index blue, bold on', 
                     num_format_str='#,##0.00')
style2 = xlwt.easyxf(num_format_str='D-MMM-YY')

ws.write(0, 0, datetime.now(), style2)
ws.write(0, 1, datetime.now().strftime("%B"), style2)
ws.write(0, 2, datetime.now().strftime("%A"), style2)
ws.write(1, 0, 5369.2, style1)
ws.write(1, 1, 1926.5, style1)
ws.write(1, 2, 4896.2, style1)
ws.write(2, 0, 5)
ws.write(2, 1, 10)
ws.write(2, 2, xlwt.Formula("A3+B3"))

wb.save('xlwt_output.xls')

3. xlsxwriter (สำหรับ .xlsx - Excel 2007+, ฟีเจอร์มากที่สุด)

รองรับ chart, image, conditional format, autofilter, data validation, vba

import xlsxwriter

wb = xlsxwriter.Workbook('xlsxwriter_output.xlsx')
ws = wb.add_worksheet()

ws.set_column('A:A', 18)
bold = wb.add_format({'bold': True})

ws.write('A1', 'Freelancer', bold)
ws.write('A2', 'Work')
ws.write('A3', 100)
ws.write('A4', 1000)

ws.write('B1', 'DECIMAL', bold)
ws.write('B2', 17.1)
ws.write('B3', 29.6)
ws.write('B4', 45.9)

# Insert image
ws.insert_image('E5', 'firefox.jpg')

wb.close()

เปรียบเทียบ

ไลบรารีรองรับFormattingChart/ImageRead/Write
openpyxl.xlsxดีChart ใช่, Image ใช่Read/Write
xlwt.xlsดีไม่รองรับWrite only
xlsxwriter.xlsxดีเยี่ยมChart/Image ใช่Write only
xlrd.xls/.xlsx--Read only (legacy)

สรุป

  • ต้องอ่านไฟล์มีอยู่ → openpyxl
  • เขียนไฟล์ใหม่ .xlsx ฟีเจอร์เต็ม → xlsxwriter
  • ต้องสร้าง .xls เก่า → xlwt