使用Python在Excel中插入文本框

0 投票
1 回答
76 浏览
提问于 2025-04-12 18:44

我想用Python在Excel表格中插入一个文本框,我试过openpyxl、openpyxl.drawing.shape,具体来说,还有xlsxwriter,但就是不行。

from openpyxl import Workbook
from openpyxl.drawing.text import Paragraph, ParagraphProperties
from openpyxl.drawing.text import CharacterProperties
from openpyxl.drawing.shape import Shape

# Create a shape
shape = Shape()

# Initialize GraphicalProperties
graphical_properties = GraphicalProperties()

# Assign GraphicalProperties to spPr
shape.spPr = graphical_properties

# Add the shape to the worksheet
sheet.add_shape(shape)

# Save the workbook
workbook.save("output.xlsx")

这是我尝试过的最新代码。

1 个回答

2

Openpyxl在处理图形方面表现得不太好,所以更推荐使用Xlsxwriter。如果你想在已有的工作簿上添加内容,可以选择Xlwings或者win32com。

下面的代码是Xlwings的一个示例;

AddShape命令是Excel里的一个功能,形状的类型来自于MsoAutoShapeType枚举,比如1代表矩形,9代表圆形。

import xlwings as xw
from xlwings.utils import rgb_to_int

excel_file = 'shapes.xlsx'
with xw.App(visible=True) as app:
    wb = xw.Book(excel_file)
    ws = wb.sheets('Sheet1')

    ### Excel AddShape command, Values are Type, Left, Top, Width & Height
    shape1 = ws.api.Shapes.AddShape(1, 100, 50, 150, 30)  # 1 is a rectangle
    shape2 = ws.api.Shapes.AddShape(9, 1, 1, 20, 20)  # 9 is a circle

    shape1_name = shape1.Name
    shape1.Fill.ForeColor.RGB = rgb_to_int((255,233,0))

    shape2.TextFrame2.TextRange.Text = "Hello There"

    ### Some parameters are accessible from ws.shapes
    for shape in ws.shapes:
        if shape.name == shape1_name:
            shape.characters.api.Text = f"Shape Name = {shape.name}"
            shape.characters.font.name = 'Arial'
            shape.characters.font.color = (0,0,0)
            shape.characters.font.bold = True

            ### You can also add a macro to the object
            # shape.api.OnAction = "sample_sub"

    wb.save(excel_file)

enter image description here

撰写回答