繁体   English   中英

用C#表单中的文本替换Word中的文本

[英]Replace text in Word with text from C# form

我正在尝试使用C#编写应用程序。 按下单选按钮时,我想打开一个Microsoft Word文档(发票),并用“表单”中的文本替换一些文本。 Word文档还包含一些带有文本的文本框。

我已经尝试实现此链接中编写的代码。Word Automation查找和替换(不包括文本框),但是当我按下单选按钮时,出现一个窗口,询问“使文档可读的编码”,然后打开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();

除非您想将所有值都传递给函数,否则这段代码应该可以使您正常运行。

编辑:如果您需要更多示例,我也正在撰写博客文章,因此如果这对于您的用例而言不够清楚,我将有更多详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM