c# - 向使用 OpenXML 创建的电子表格文档中的单元格添加注释
问题描述
我正在使用 openXML 创建一个 xlsx 文件。我想向某些行单元格添加注释。有没有办法在单元格中添加评论。或者我应该使用 Microsoft.Office.Interop 向 excel 单元格添加注释?
解决方案
我使用了适用于 Microsoft Office 的 Open XML SDK Productivity Tool,它允许您加载 Excel 或 Word 文件,然后发出 C# 代码来生成该文件。
然后我创建了一个带有评论的文件。首先,我尝试了两条评论,但它生成的代码量让我很难分辨出什么是什么。
结果不好看。你可以减少很多,并可能消除一些。但这是一种了解幕后情况的方法。
您也可以跳过所有这些,只使用EPPlus,在查看接下来会发生什么之后,您可以想象为什么有人觉得有必要让这更容易。
关键步骤是:
- 创建一个新的
Comments
- 创建一个新的
CommentsList
(?!!!) - 创建一个新的
Comment
,它具有Reference
指示它属于哪个单元格的属性 - 创建一个新的
CommentText
- 创建一个新的
Run
- 附加
Run
到CommentText
- 附加
CommentText
到Comment
- 附加
Comment
到CommentsList
- 附加
CommentsList
到Comments
将
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; }
推荐阅读
- ssis - VS 2015 的 SSIS 脚本任务未显示断点
- firebase-hosting - next.js 与 firebase 托管:如何为 firebase 创建 404.html 文件?
- html - 如何将项目左对齐(标题)
- angularjs - Angular 1.5 与外部值相关的自定义验证
- java - 如何在服务器上实现校验和检查逻辑以识别 jar 是否相同或更新
- python - 有谁知道如何使用 CVXOPT 模块在 Python 中进行凸优化?
- sql - 结合 join 和 where 子句时性能不佳
- c# - 如何对 KeyValuePair 的特定列进行分组
- php - 致命错误:调用未定义函数:WP functions.php
- recursion - Lua Love2d 四叉树递归