Cách làm việc với bảng trong Python

Cách làm việc với bảng trong Python

Aspose.Slides FOSS for Python supports creating tables on slides with configurable column widths and row heights. This guide shows how to add a table, populate it with data, and apply basic text formatting to cells.

Hướng Dẫn Từng Bước

Bước 1: Cài Đặt Gói

pip install aspose-slides-foss

Bước 2: Tạo hoặc Mở một Bản trình bày

import aspose.slides_foss as slides
from aspose.slides_foss.export import SaveFormat

with slides.Presentation() as prs:
    slide = prs.slides[0]
    # ... add table ...
    prs.save("table.pptx", SaveFormat.PPTX)

Bước 3: Xác định Độ rộng Cột và Chiều cao Hàng

Bảng yêu cầu độ rộng cột và chiều cao hàng được chỉ định rõ ràng bằng điểm (1 point = 1/72 inch). Một slide tiêu chuẩn có độ rộng 720 điểm và chiều cao 540 điểm.

col_widths = [200.0, 150.0, 150.0]   # 3 columns: 200pt + 150pt + 150pt
row_heights = [45.0, 40.0, 40.0]     # 3 rows: 45pt header + 40pt data rows

Bước 4: Thêm Bảng

slide.shapes.add_table(x, y, col_widths, row_heights) tạo bảng tại vị trí (x, y):

import aspose.slides_foss as slides
from aspose.slides_foss.export import SaveFormat

with slides.Presentation() as prs:
    slide = prs.slides[0]

    col_widths = [200.0, 150.0, 150.0]
    row_heights = [45.0, 40.0, 40.0]
    table = slide.shapes.add_table(50, 100, col_widths, row_heights)

    prs.save("table.pptx", SaveFormat.PPTX)

Bước 5: Đặt Văn bản cho Ô

Truy cập các ô qua table.rows[row_index][col_index] và gán văn bản thông qua .text_frame.text:

import aspose.slides_foss as slides
from aspose.slides_foss.export import SaveFormat

with slides.Presentation() as prs:
    slide = prs.slides[0]

    col_widths = [200.0, 150.0, 150.0]
    row_heights = [45.0, 40.0, 40.0]
    table = slide.shapes.add_table(50, 100, col_widths, row_heights)

    # Header row (row 0)
    headers = ["Product", "Units Sold", "Revenue"]
    for col, header in enumerate(headers):
        table.rows[0][col].text_frame.text = header

    # Data rows
    data = [
        ["Widget A", "1,200", "$24,000"],
        ["Widget B", "850", "$17,000"],
    ]
    for row_idx, row_data in enumerate(data):
        for col, cell_text in enumerate(row_data):
            table.rows[row_idx + 1][col].text_frame.text = cell_text

    prs.save("sales-table.pptx", SaveFormat.PPTX)

Bước 6: Định dạng Văn bản Ô Tiêu đề

Áp dụng định dạng in đậm cho các ô tiêu đề bằng PortionFormat:

from aspose.slides_foss import NullableBool, FillType
from aspose.slides_foss.drawing import Color

for col in range(len(headers)):
    cell = table.rows[0][col]
    portions = cell.text_frame.paragraphs[0].portions
    if portions:
        fmt = portions[0].portion_format
        fmt.font_bold = NullableBool.TRUE
        fmt.fill_format.fill_type = FillType.SOLID
        fmt.fill_format.solid_fill_color.color = Color.from_argb(255, 255, 255, 255)

Ví dụ Hoạt động Đầy đủ

import aspose.slides_foss as slides
from aspose.slides_foss import NullableBool, FillType
from aspose.slides_foss.drawing import Color
from aspose.slides_foss.export import SaveFormat

data_rows = [
    ["North", "$1.2M", "+8%"],
    ["South", "$0.9M", "+4%"],
    ["East",  "$1.5M", "+12%"],
    ["West",  "$0.7M", "+2%"],
]
headers = ["Region", "Revenue", "Growth"]

with slides.Presentation() as prs:
    slide = prs.slides[0]

    col_widths = [180.0, 140.0, 120.0]
    row_heights = [45.0] + [38.0] * len(data_rows)

    table = slide.shapes.add_table(60, 80, col_widths, row_heights)

    # Header row
    for col, text in enumerate(headers):
        cell = table.rows[0][col]
        cell.text_frame.text = text
        if cell.text_frame.paragraphs and cell.text_frame.paragraphs[0].portions:
            fmt = cell.text_frame.paragraphs[0].portions[0].portion_format
            fmt.font_bold = NullableBool.TRUE

    # Data rows
    for row_idx, row_data in enumerate(data_rows):
        for col, text in enumerate(row_data):
            table.rows[row_idx + 1][col].text_frame.text = text

    prs.save("regional-revenue.pptx", SaveFormat.PPTX)

print("Saved regional-revenue.pptx")

Các Vấn Đề Thường Gặp và Cách Khắc Phục

IndexError khi truy cập table.rows[row][col]

Chỉ số hàng và cột bắt đầu từ 0. Nếu bạn đã định nghĩa row_heights với 3 phần tử, các chỉ số hàng hợp lệ là 0, 1, 2.

Văn bản ô không hiển thị trong tệp đã lưu

Luôn gán thông qua .text_frame.text, không phải qua .text trực tiếp trên đối tượng ô:

# Correct
table.rows[0][0].text_frame.text = "Header"

# Wrong: AttributeError or silent failure
table.rows[0][0].text = "Header"

Vị trí bảng bị lệch khỏi slide

Kiểm tra rằng x + sum(col_widths) <= 720y + sum(row_heights) <= 540 cho một slide tiêu chuẩn.


Câu hỏi thường gặp

Tôi có thể hợp nhất các ô trong bảng không?

Việc gộp ô không được hỗ trợ trong phiên bản này.

Tôi có thể áp dụng màu nền cho toàn bộ bảng không?

Áp dụng định dạng tô màu cho từng ô riêng lẻ:

for row_idx in range(len(table.rows)):
    for col_idx in range(len(table.rows[row_idx])):
        cell = table.rows[row_idx][col_idx]
        cell.fill_format.fill_type = FillType.SOLID
        cell.fill_format.solid_fill_color.color = Color.from_argb(255, 240, 248, 255)

Tôi có thể đặt kiểu viền cho ô không?

Các thuộc tính viền ô có thể truy cập qua table.rows[row][col].border_* các thuộc tính. Tham khảo tài liệu API để biết danh sách đầy đủ các thuộc tính định dạng viền.


Xem thêm

 Tiếng Việt