我真的很想用 openpyxl 库绘制一个带有锚点到单元格的弯曲箭头连接器,如下图所示;
在查看官方文档后,我找不到执行此操作的方法,(尽管我在 class openpyxl.drawing.shapes.PresetGeometry2D 中找到了一些相关关键字)
如何用Python绘制这种锚定连接器?如果 OpenPyxl 无法提供此功能,我愿意接受其他软件包。
Openpyxl 通常不能很好地与 Shapes 配合使用,但使用像 Xlwings 或 Win32com 这样的替代模块通常是更好的选择;
以下是在 Xlwings 中执行此操作的基本示例;
代码示例
(注意 win32com 的命令与此类似)
import xlwings as xw
from xlwings.utils import rgb_to_int
with xw.App(visible=True) as app:
wb = xw.Book()
ws = wb.sheets.active
# Add two rectangle shapes
### Excel AddShape command, Values are Type, Left, Top, Width & Height
shape1 = ws.api.Shapes.AddShape(1, 50, 44, 95, 27) # 1 is a rectangle
print(f"Shape1 name '{shape1.Name}'")
shape1.Fill.ForeColor.RGB = rgb_to_int((255, 233, 00)) # Set Fill colour
shape2 = ws.api.Shapes.AddShape(1, 290, 115, 94, 28)
print(f"Shape2 name '{shape2.Name}'")
shape2.Fill.ForeColor.RGB = '&HFF0000' # Alternate method to set fill colour
### AddConnector (line) has same params; Type, Left, Top, Width & Height
connector1 = ws.api.Shapes.AddConnector(3, 1, 1, 1, 1) # 3 is a msoConnectorCurve (Curved connector)
# connector1.Line.ForeColor.RGB = '&H000000' # Set Line colour method 1
# connector1.Line.ForeColor.RGB = rgb_to_int((0, 0, 0)) # Set Line colour method 2
connector1.Line.ForeColor.ObjectThemeColor = 13 # Set line colour method 3
connector1.Line.EndArrowheadStyle = 2 # Set Arrow head style as desired
connector1.Line.EndArrowheadLength = 3 # Set Arrow head length as desired
connector1.Line.EndArrowheadWidth = 3 # Set Arrow head width as desired
### Connecting the curved connector between the two rectangles
connector1.ConnectorFormat.BeginConnect(ConnectedShape=shape1, ConnectionSite=1)
connector1.ConnectorFormat.EndConnect(ConnectedShape=shape2, ConnectionSite=1)
### Re-route the connectors to the shortest route between the two shapes
connector1.RerouteConnections()
wb.save('Shapes.xlsx')
结果表
其他详细信息
对于 AddShape 命令的第一个参数,“Type”是要添加的形状类型。这些是 Excel 枚举类型,因此可以是名称或数字,
IE。 msoShapeRectangle(矩形)枚举为 1,因此“msoShapeRectangle”或 1 都可以用作类型。
其余参数是代码中注明的形状的位置和大小。
我使用任意值来放置矩形。
连接器的尺寸和位置也可以确定。然而,由于我们在两个形状之间连接它,我们可以使用任意值,并将其留给 Excel 连接起点和终点,这就是为什么我在本例中将它们全部设置为 1。
连接两个形状之间的弯曲连接器时,您需要指定起始形状和起始形状上要连接的点(连接位置)以及结束形状和结束形状上要连接的连接位置。
连接部位以数字表示,根据形状的不同而有所不同。如果您知道所需的连接站点值是多少,则可以指定它。
在示例中,我使用的矩形 1 连接站点为 4,矩形 2 连接站点为 2,因此命令可能是;
connector1.ConnectorFormat.BeginConnect(ConnectedShape=shape1, ConnectionSite=4)
connector1.ConnectorFormat.EndConnect(ConnectedShape=shape2, ConnectionSite=2)
但是,如果连接器站点编号未知,您可以像我在此处所做的那样连接到任意两个点,然后让 Excel 使用
RerouteConnections()
将连接器重新路由到最短路线