Select 以编程方式创建一个形状

Select a shape programmatically

如何以编程方式 (C#) select SpreadsheetGear 中的形状(或图表)?

我试过:

1. IShape.select(false); // failed
2. ShapeSelection = ...; // failed

IShape.Select(...) is the correct API needed to select a shape. I do see you passed in false for the "replace" parameter, which means you are adding this new shape to any other shapes that were already selected (i.e., IWorksheetWindowInfo.ShapeSelection.Count 将为 2 或更大)。如果要替换当前的形状选择,则需要传入 true

下面是一些示例代码,演示了在 sheet 上选择一个或多个形状并使用一些 Console.WriteLine(...) 验证此行为,但我也验证了此行为时在 SpreadsheetGear 的 WorkbookView UI 控件上查看这些操作:

// Create a workbook and a couple shapes on the active worksheet.
IWorkbook workbook = Factory.GetWorkbook();
IWorksheet worksheet = workbook.ActiveWorksheet;
IShape shape1 = worksheet.Shapes.AddShape(AutoShapeType.Rectangle, 5, 5, 50, 50);
IShape shape2 = worksheet.Shapes.AddShape(AutoShapeType.Oval, 75, 57, 50, 50);

// Ensure no shapes are selected.
IShapeRange shapeSelection = worksheet.WindowInfo.ShapeSelection;
Console.WriteLine($"ShapeSelection is null? {shapeSelection == null}");
// OUTPUT: ShapeSelection is null? True

// Select shape1 ("Rectangle 1")
shape1.Select(true);
shapeSelection = worksheet.WindowInfo.ShapeSelection;
Console.WriteLine($"ShapeSelection: Count={shapeSelection.Count}, Name[0]={shapeSelection[0].Name}");
// OUTPUT: ShapeSelection: Count=1, Name[0]=Rectangle 1

// Select shape2 ("Oval 2")
shape2.Select(true);
shapeSelection = worksheet.WindowInfo.ShapeSelection;
Console.WriteLine($"ShapeSelection: Count={shapeSelection.Count}, Name[0]={shapeSelection[0].Name}");
// OUTPUT: ShapeSelection: Count=1, Name[0]=Oval 2

// Select both shapes (false passed into IShape.Select(...))
shape1.Select(false);
shapeSelection = worksheet.WindowInfo.ShapeSelection;
Console.WriteLine($"ShapeSelection: Count={shapeSelection.Count}, Name[0]={shapeSelection[0].Name}, Name[1]={shapeSelection[1].Name}");
// OUTPUT: ShapeSelection: Count=2, Name[0]=Oval 2, Name[1]=Rectangle 1