我正在尝试用 C# 制作一个应用程序。当按下单选按钮时,我想打开一个 Microsoft Word 文档(发票)并用我的表单中的文本替换一些文本。 Word 文档还包含一些带有文本的文本框。
我尝试实现此链接 Word Automation Find and Replace not including Text Boxes 中编写的代码但是当我按下单选按钮时,会出现一个窗口,询问“使文档可读的编码”,然后 Word 文档打开,里面充满了黑色三角形和其他内容,而不是我最初的发票模板。
这是我尝试过的:
string documentLocation = @"C:\\Documents\\Visual Studio 2015\\Project\\Invoice.doc";
private void yes_radioBtn_CheckedChanged(object sender, EventArgs e)
{
FindReplace(documentLocation, "HotelName", "MyHotelName");
Process process = new Process();
process.StartInfo.FileName = documentLocation;
process.Start();
}
private void FindReplace(string documentLocation, string findText, string replaceText)
{
var app = new Microsoft.Office.Interop.Word.Application();
var doc = app.Documents.Open(documentLocation);
var range = doc.Range();
range.Find.Execute(FindText: findText, Replace: WdReplace.wdReplaceAll, ReplaceWith: replaceText);
var shapes = doc.Shapes;
foreach (Shape shape in shapes)
{
var initialText = shape.TextFrame.TextRange.Text;
var resultingText = initialText.Replace(findText, replaceText);
shape.TextFrame.TextRange.Text = resultingText;
}
doc.Save();
doc.Close();
Marshal.ReleaseComObject(app);
}
最佳答案
因此,如果您的单词模板每次基本上都是相同的
- 复制模板
- 处理模板
- 以所需格式保存
- 删除模板副本
您要在 Word 文档中替换的每个部分都必须为该位置插入书签(在区域中输入文本的最简单方法)。
我总是创建一个函数来完成此任务,并且最终传递路径以及所有文本来替换我的文档内书签。函数调用有时可能会很长,但它对我有用。
Application app = new Application();
Document doc = app.Documents.Open("sDocumentCopyPath.docx");
if (doc.Bookmarks.Exists("bookmark_1"))
{
object oBookMark = "bookmark_1";
doc.Bookmarks.get_Item(ref oBookMark).Range.Text = My Text To Replace bookmark_1;
}
if (doc.Bookmarks.Exists("bookmark_2"))
{
object oBookMark = "bookmark_2";
doc.Bookmarks.get_Item(ref oBookMark).Range.Text = My Text To Replace bookmark_2;
}
doc.ExportAsFixedFormat("myNewPdf.pdf", WdExportFormat.wdExportFormatPDF);
((_Document)doc).Close();
((_Application)app).Quit();
除非您想将所有值传递到函数中,否则此代码应该可以让您启动并运行。
编辑:如果您需要更多示例,我也在撰写博客文章,因此如果这对于您的用例来说还不够清晰,我会提供更多详细信息。
关于c# - 将 Word 中的文本替换为 C# 表单中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42865541/