2014-11-04 37 views
0

我正在使用C#的excel工作,但我在将图片注释插入到excel时遇到了一些问题。 这里是我的代码:用C#插入图片评论好的,但复制评论内容失败

public void InstertPictureComment(Excel.Range myrange, string picturepath) 
{ 
    myrange.ClearComment(); 
    myrange.AddComment(); 
    myrange.Comment.Shape.Fill.UserPicture(picturepath); 
    myrange.Comment.Shape.Width=400; 
    myrange.Comment.Shapes.Height=300; 
} 

上面的代码工作得很好,我可以成功地插入图片评论。 但是,问题出现了。 复制的内容(与图片评论我刚刚插入)到其他Excel工作表 ==>保存Excel,并关闭Excel应用 ==>重新打开Excel和一个消息告诉“Excel中发现XXXXX不可读的内容”

我的代码有什么问题?或者这是一个超级问题?

回答

0

我已经纠正了代码,以便它编译问题

public void InstertPictureComment(Excel.Range myrange, string picturepath) 
{ 
    myrange.Cells.ClearComments(); 
    myrange.AddComment(); 
    myrange.Comment.Shape.Fill.UserPicture(picturepath); 
    myrange.Comment.Shape.Width = 400; 
    myrange.Comment.Shape.Height = 300; 
} 

部分与Excel。使用你的代码,你可能正在创建一个新的Excel应用程序实例。 Excel无法跨应用程序实例复制对象。

如果您在同一应用程序实例中打开另一个工作簿,则这些对象将被复制。跨应用程序实例复制数据的唯一方法是使用“粘贴特殊功能”。

您应该获取现有的Excel应用程序实例。如果它不在那里,那么你可以创建它。

private Excel.Application GetExcelInstance() 
{ 
    Excel.Application instance = null; 
    try 
    { 
     instance = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); 
    } 
    catch (System.Runtime.InteropServices.COMException ex) 
    { 
     instance = new Excel.Application(); 
     appCreatedExcelInstance = true; 
    } 

    return instance; 
} 

您可以使用appCreatedExcelInstance标志来决定是否在清理期间退出实例。