Search code examples
exceltypescriptoffice-scripts

Connecting shapes with a line in Microsoft Excel OfficeScript (TypeScript)


I am trying to connect two shapes with a line in Excel using OfficeScript, which is a superset of TypeScript, which is a superset of JavaScript.

I used Google Gemini to try and figure out the answer, and got this. It perfectly describes what I'm trying to do as pseudocode, but the worksheet object does not have the method insertConnector(), so it does not work.

// Get the two shapes you want to connect
const startShape = worksheet.getShapes().getByName("startShapeName");
const endShape = worksheet.getShapes().getByName("endShapeName");

// Create a connector object
const connector = worksheet.insertConnector(startShape, endShape);

// Choose a connector type (e.g., straight, elbow, etc.)
connector.setConnectorType(Excel.ConnectorType.Straight);

// Format the connector (optional)
connector.strokeLine({ color: "red" })

As an example, this is what I am trying to get as an end result:

EndResult


Solution

    • Using connectBeginShape and connectEndShape to connect line to desired shapes

    Microsoft documentation:

    ExcelScript.Line interface

    function main(workbook: ExcelScript.Workbook) {
        let selectedSheet = workbook.getActiveWorksheet();
        const FLOW_CHRT_DECI = ExcelScript.GeometricShapeType.flowChartDecision;
        let fcDecision1 = selectedSheet.addGeometricShape(FLOW_CHRT_DECI);
        fcDecision1.setLeft(40);
        fcDecision1.setTop(40);
        fcDecision1.setWidth(40);
        fcDecision1.setHeight(40);
        let fcDecision2 = selectedSheet.addGeometricShape(FLOW_CHRT_DECI);
        fcDecision2.setLeft(160);
        fcDecision2.setTop(40);
        fcDecision2.setWidth(40);
        fcDecision2.setHeight(40);
        // add a line
        let connLine = selectedSheet.addLine(0, 0, 10, 10, ExcelScript.ConnectorType.straight);
        // connect shapes
        connLine.getLine().connectBeginShape(fcDecision1, 3);
        connLine.getLine().connectEndShape(fcDecision2, 1);
    }
    

    enter image description here