使用现有单词.doc查找并替换为.net核心



我正在尝试在我创建并添加到.net核心项目的word文档模板中查找和替换特定的单词/字符串。

我目前正在使用NPOI来做这件事,但我似乎无法理解,因为我的C#知识不太好!

理论上,我想阅读现成的.docx模板,然后替换我需要的,然后保存它。

我已经尝试了我能想到的一切,但仍然没有成功。

这是我留下的代码:

var docUrl = @"App_Data/Document_Template.docx";
using (FileStream file = new FileStream(docUrl, FileMode.Open, FileAccess.Read))
{
XWPFDocument doc = new XWPFDocument(file);
// get the document template using docUrl and replace string with another string.
doc.Write(file);
}

任何帮助都会很棒,因为我花了这么多时间研究和尝试实现这一点,但运气不佳!

对于MS word中的替换特定单词,首先您应该从nuget添加以下引用:

Install-Package Microsoft.Office.Interop.Word

此示例代码将指定的字符串替换为另一个字符串:

namespace MSWordReplacement
{
class Program
{
static void Main(string[] args)
{
Application app = new Application();
Document doc = app.Documents.Open(@"C:Sample.docx");
// Assign a search string to a variable.
object findText = "Find me.";
// Clear formatting from previous searches.
app.Selection.Find.ClearFormatting();
if (app.Selection.Find.Execute(ref findText))
{
// Replace new text.
app.Selection.Text = "You found me!";
}
else
{
// Do somthing else.
}
doc.Close(true);
app.Quit();
}
}
}

作为警告,你应该知道这个软件包正在工作,但它可能与dot-net-core不完全兼容!

有关更多信息,请使用此链接:以程序方式搜索和替换文档中的文本

最新更新