namespace OperateExcel
{
class Program
{
private static object oMis = System.Reflection.Missing.Value; static void Main(string[] args)
{
Excel.Application xApp = new Excel.ApplicationClass(); xApp.Visible = true;
Excel.Workbook xBook = xApp.Workbooks._Open(@"D:\Empowerment Export Data Format.xls",
oMis, oMis, oMis, oMis
, oMis, oMis, oMis, oMis
, oMis, oMis, oMis, oMis); Excel.Worksheet xSheet = (Excel.Worksheet)xBook.Sheets[1]; Excel.Range rng1 = xSheet.get_Range("A1", Type.Missing); Excel.Shape orgChart = xSheet.Shapes.AddDiagram(MsoDiagramType.msoDiagramOrgChart, 10, 10, 400, 200);
orgChart.Name = "test";

Excel.DiagramNode node = orgChart.DiagramNode;
Excel.DiagramNodeChildren children = node.Children;
Excel.DiagramNode newNode = children.AddNode(0, MsoDiagramNodeType.msoDiagramNode);
Excel.Shape textShape = newNode.TextShape; // 这里报错 Specified cast is not valid.
Excel.TextFrame textFrame = textShape.TextFrame;
textFrame.Characters(0, 1).Caption = "test"; Excel.DiagramNode n1 = newNode.Children.AddNode(0, MsoDiagramNodeType.msoDiagramNode);
Excel.DiagramNode n2 = newNode.Children.AddNode(0, MsoDiagramNodeType.msoDiagramNode);
}
}
}
以上是我的代码, 但是每次他都报错如下
Specified cast is not valid.奇怪的是 newNode.TextShape 也是Excel.Shape类型的
同一个类型之间居然也转换出错??

解决方案 »

  1.   

    Excel.Shape textShape = newNode.TextShape; // 这里报错 Specified cast is not valid.使用Excel.Shape textShape = newNode.TextShape as Excel.Shape;
    然后判断textShape 是否为null
    如果要是为null说明newNode.TextShape 不能转为Excel.Shape
      

  2.   

    check if there are some fields with integer data combined with fields with text data and make it uniform for excel export to work
      

  3.   

    1 楼的感谢 但是好像不对2 楼的不太明白 我是在一个空的excel 里面插入的 应该不存在数据不一致的问题吧