如何在 C# 中向现有形状(文本框)添加文本 Excel Interop

How to add text to an existing shape(textbox) in C# Excel Interop

我有一个 excel,其中包含 textboxes/shapes,我将用特定数据填充它。我使用以下代码来识别每个形状:

//using Excel = Microsoft.Office.Interop.Excel;

Excel.Worksheet xlWorkSheet
foreach(Excel.Shape shp in xlworksheet.Shapes)
{
    //code to add text to shape goes here....
}

我也试过使用:

shp.TextFrame2.TextRange.Characters.Text = "Test";

shp.TextFrame.Characters(Type.Missing, Type.Missing).Text = "Test";

但给出一个错误,分别指出 The specified value is out of rangeMember not found. (Exception from HRESULT: 0x80020003 (DISP_E_MEMBERNOTFOUND))

向现有文本框添加文本的正确方法应该是什么?

在设置文本之前,您必须检查 Shape 的类型是否为 msoTextBox

Excel.Worksheet xlWorkSheet
foreach (Excel.Shape shp in xlworksheet.Shapes)
{
    if (shp.Type == Microsoft.Office.Core.MsoShapeType.msoTextBox)
    {
        shp.TextFrame.Characters(Type.Missing, Type.Missing).Text = "Test";
    }
}