我需要使用 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")
这是我尝试过的最新代码。
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('Sheet3')
### 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,00))
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 = "Shape Name = {}".format(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('shapes.xlsx')