首页 > 解决方案 > 向使用 OpenXML 创建的电子表格文档中的单元格添加注释

问题描述

我正在使用 openXML 创建一个 xlsx 文件。我想向某些行单元格添加注释。有没有办法在单元格中添加评论。或者我应该使用 Microsoft.Office.Interop 向 excel 单元格添加注释?

标签: c#openxmlxlsx

解决方案


我使用了适用于 Microsoft Office 的 Open XML SDK Productivity Tool,它允许您加载 Excel 或 Word 文件,然后发出 C# 代码来生成该文件。

然后我创建了一个带有评论的文件。首先,我尝试了两条评论,但它生成的代码量让我很难分辨出什么是什么。

结果不好看。你可以减少很多,并可能消除一些。但这是一种了解幕后情况的方法。

您也可以跳过所有这些,只使用EPPlus,在查看接下来会发生什么之后,您可以想象为什么有人觉得有必要让这更容易。

关键步骤是:

  • 创建一个新的Comments
  • 创建一个新的CommentsList(?!!!)
  • 创建一个新的Comment,它具有Reference指示它属于哪个单元格的属性
  • 创建一个新的CommentText
  • 创建一个新的Run
  • 附加RunCommentText
  • 附加CommentTextComment
  • 附加CommentCommentsList
  • 附加CommentsListComments
  • WorksheetCommentsPart.Comments属性设置为Comments.

    private void GenerateWorksheetCommentsPart1Content(WorksheetCommentsPart worksheetCommentsPart1)
    {
        Comments comments1 = new Comments(){ MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "xr" }  };
        comments1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
        comments1.AddNamespaceDeclaration("xr", "http://schemas.microsoft.com/office/spreadsheetml/2014/revision");
    
        Authors authors1 = new Authors();
        Author author1 = new Author();
        author1.Text = "Hannen, Scott";
    
        authors1.Append(author1);
    
        CommentList commentList1 = new CommentList();
    
        Comment comment1 = new Comment(){ Reference = "B3", AuthorId = (UInt32Value)0U, ShapeId = (UInt32Value)0U };
        comment1.SetAttribute(new OpenXmlAttribute("xr", "uid", "http://schemas.microsoft.com/office/spreadsheetml/2014/revision", "{811649EF-4CB5-4311-BE14-228133003BE4}"));
    
        CommentText commentText1 = new CommentText();
    
        Run run1 = new Run();
    
        RunProperties runProperties1 = new RunProperties();
        FontSize fontSize3 = new FontSize(){ Val = 9D };
        Color color3 = new Color(){ Indexed = (UInt32Value)81U };
        RunFont runFont1 = new RunFont(){ Val = "Tahoma" };
        RunPropertyCharSet runPropertyCharSet1 = new RunPropertyCharSet(){ Val = 1 };
    
        runProperties1.Append(fontSize3);
        runProperties1.Append(color3);
        runProperties1.Append(runFont1);
        runProperties1.Append(runPropertyCharSet1);
        Text text1 = new Text(){ Space = SpaceProcessingModeValues.Preserve };
        text1.Text = "This is my comment!\nThis is line 2!\n";
    
        run1.Append(runProperties1);
        run1.Append(text1);
    
        commentText1.Append(run1);
    
        comment1.Append(commentText1);
    
        commentList1.Append(comment1);
    
        comments1.Append(authors1);
        comments1.Append(commentList1);
    
        worksheetCommentsPart1.Comments = comments1;
    }
    

推荐阅读