2014-11-04 109 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標誌來決定是否在清理期間退出實例。