【发布时间】:2017-03-17 19:18:25
【问题描述】:
我正在尝试用 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);
}
【问题讨论】:
-
我不得不在第一行停止阅读。 @ 前缀的目的是避免转义,所以应该有一个反斜杠,如果我没记错的话
-
@dlatikay 在某些情况下双重工作同样出色 - 尽管我之前遇到过导致问题的情况。
-
生成的文件已损坏,但没有理由责怪您的代码,到目前为止看起来还不错。您可以改用 .docx 格式吗?有一个功能问题可能成为问题。如果替换文本偶然包含要在后续调用中替换的文本怎么办 - 那会搞砸。考虑使用书签而不是全部替换。
标签: c# ms-word office-interop