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

时间:2015-10-20 06:18:45

标签: c# excel excel-interop

我有一个包含文本框/形状的excel,我将用特定数据填写。我在识别每个形状时使用了以下代码:

//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))

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

1 个答案:

答案 0 :(得分:5)

在设置文字之前,您必须检查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";
    }
}