如何使用 Microsoft.Office.Interop.Word 在 C# 中编辑 docx 文件

How to edit docx file in C# using Microsoft.Office.Interop.Word

我需要将 docx 文件中的用户元标记 #likethis# 替换为数据库中的值。直接编辑文件的字节数组替换简单的字符串很好。但是当我需要加载 table 数据时,它变得更加复杂。所以我不得不尝试使用这个库,但它的文档很差。

我在这个参考资料中找到了如何用值替换书签 https://social.msdn.microsoft.com/Forums/Lync/en-US/ed7278b1-1fc7-44d5-9e87-4c3e41a110cf/how-to-modify-bookmarked-fields-in-word-docx-file-from-code?forum=worddev

但是有一种方法可以追踪文本中的字符串并将其替换为任何内容(如其他文本、table 或徽标等图像)?

Considerations for server-side Automation of Office 文章陈述如下:

Microsoft strongly recommends that developers find alternatives to Automation of Office if they need to develop server-side solutions. Because of the limitations to Office's design, changes to Office configuration are not enough to resolve all issues. Microsoft strongly recommends a number of alternatives that do not require Office to be installed server-side, and that can perform most common tasks more efficiently and more quickly than Automation. Before you involve Office as a server-side component in your project, consider alternatives.

Most server-side Automation tasks involve document creation or editing. Office 2007 supports new Open XML file formats that let developers create, edit, read, and transform file content on the server side. These file formats use the System.IO.Package.IO namespace in the Microsoft .NET 3.x Framework to edit Office files without using the Office client applications themselves. This is the recommended and supported method for handling changes to Office files from a service.

作为解决方法,您可以考虑使用 Open XML SDK 打开 XML 文档。或者只是为服务器端执行而设计的任何第三方包装器(例如,Aspose)。