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

Python - วาดกราฟใน Excel ด้วย OpenPyXL

OpenPyXL เป็นไลบรารี Python สำหรับทำงานกับ Excel: อ่าน เขียน คำนวณ และวาดกราฟ

ตัวอย่างโค้ด: Bubble Chart


import openpyxl
from openpyxl.chart import BubbleChart, Reference, Series

# สร้าง Workbook ใหม่
wb = openpyxl.Workbook()
sheet = wb.active

# ข้อมูล: (Number of Products, Sales in USD, Market share)
rows = [
    ("Number of Products", "Sales in USD", "Market share"),
    (14, 12200, 15),
    (20, 60000, 33),
    (18, 24400, 10),
    (22, 32000, 42),
]

for row in rows:
    sheet.append(row)

# สร้าง Bubble Chart
chart = BubbleChart()

# กำหนดข้อมูลสำหรับแกน X, Y และขนาดฟอง
xvalues = Reference(sheet, min_col=1, min_row=2, max_row=5)
yvalues = Reference(sheet, min_col=2, min_row=2, max_row=5)
size = Reference(sheet, min_col=3, min_row=2, max_row=5)

# สร้าง Series
series = Series(values=yvalues, xvalues=xvalues, zvalues=size, title="2013")
chart.series.append(series)

# ตั้งค่ากราฟ
chart.title = "BUBBLE CHART"
chart.x_axis.title = "X_AXIS"
chart.y_axis.title = "Y_AXIS"

# แทรกกราฟ
sheet.add_chart(chart, "E2")

# บันทึกไฟล์
wb.save("bubbleChart.xlsx")

ความแตกต่าง: XlsxWriter vs OpenPyXL

คุณสมบัติXlsxWriterOpenPyXL
เขียนไฟล์ .xlsx✅ ดีเยี่ยม✅ ดี
อ่านไฟล์ .xlsx ที่มีอยู่❌ ไม่ได้✅ ได้
แก้ไขไฟล์ที่มีอยู่❌ ไม่ได้✅ ได้
Charts✅ รองรับมาก, ควบคุมละเอียด✅ รองรับพอสมควร
Formatting✅ ครบครัน✅ ครบครัน
Performance (ใหญ่)✅ เร็วกว่า, ใช้หน่วยความจำน้อยช้ากว่า, ใช้ RAM มาก
Charts 3D❌ ไม่รองรับ✅ รองรับ

Chart Types ใน OpenPyXL


from openpyxl.chart import (
    BarChart, BarChart3D,
    LineChart, LineChart3D,
    PieChart, PieChart3D,
    ScatterChart,
    AreaChart, AreaChart3D,
    BubbleChart,
    RadarChart,
    StockChart,
    SurfaceChart, SurfaceChart3D,
)

ตัวอย่างเพิ่มเติม: Bar Chart


from openpyxl.chart import BarChart, Reference

chart = BarChart()
chart.type = "col"  # "col" = column, "bar" = horizontal bar
chart.style = 10
chart.title = "Bar Chart"
chart.x_axis.title = "Category"
chart.y_axis.title = "Value"

data = Reference(sheet, min_col=2, min_row=1, max_row=5, max_col=3)
cats = Reference(sheet, min_col=1, min_row=2, max_row=5)
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)
chart.shape = 4  # Marker shape

sheet.add_chart(chart, "E2")

การติดตั้ง


pip install openpyxl

สรุป

  • ใช้ XlsxWriter เมื่อ: สร้างไฟล์ใหม่, ต้องการ chart สวย/ละเอียด, performance สำคัญ
  • ใช้ OpenPyXL เมื่อ: ต้องอ่าน/แก้ไขไฟล์ที่มีอยู่, ต้องการ 3D charts
  • ทั้งคู่ใช้ Reference objects สำหรับกำหนดช่วงข้อมูล