【C#】C#使用Microsoft.Office.Interop.Word操作Word文档,替换文本

发布于:2023-04-27 ⋅ 阅读:(1322) ⋅ 点赞:(1)

最近要做一个批量打印文档功能,于是找了Microsoft.Office.Interop.Word这个插件。

基本步骤是这样的,创建Word模板文档,C#调用模板文档替换对应的文本,保存新文档。

下面仅仅是测试代码

1.创建模板文档

新建Word文档,新建表格,要替换的文本使用花括号标记

2.代码调用模板

C#代码调用模板,替换对应文本,另存为新文档

try
{
    Application app = new Application();

    string templetFileName = @"E:\BT\Test.docx";
    string newFileName = $@"E:\BT\Test{DateTime.Now.ToString("yyyyMMddHHmmss")}.docx";
    //File.Copy(templetFileName, newFileName);

    object oMissing = System.Reflection.Missing.Value;
    object replace = WdReplace.wdReplaceAll;
    //object objNewFileName = newFileName;
    //Document doc = app.Documents.Open(ref objNewFileName,
    //    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
    //    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
    //    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
    Document doc = app.Documents.Open(templetFileName);

    Dictionary<string, string> dicDatas = new Dictionary<string, string>()
    {
        { "{姓名}","Bob" },{ "{年龄}","18" },{ "{身份}","学生" }
    };

    foreach (var item in dicDatas)
    {
        app.Selection.Find.ClearFormatting();
        app.Selection.Find.Replacement.ClearFormatting();
        app.Selection.Find.Text = item.Key;
        app.Selection.Find.Replacement.Text = item.Value;

        app.Selection.Find.Execute(
            ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing, ref replace, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing);

    }

    //doc.Save();
    doc.SaveAs2(newFileName);

    //doc.Close(ref oMissing, ref oMissing, ref oMissing);
    //app.Quit(ref oMissing, ref oMissing, ref oMissing);
    doc.Close();
    app.Quit();
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}

Console.WriteLine("Success");
Console.ReadKey();

3.效果

完成wc......

参考:

http://www.bubuko.com/infodetail-2735240.html

https://blog.csdn.net/weixin_30263277/article/details/99246703


网站公告

今日签到

点亮在社区的每一天
去签到