C#+NPOI动态库 对Word的简单编辑

众里寻他千百度,终回首,就在灯火阑珊处。

在很多人博客上看见基于NPOI动态库对word进行读写,但是没有自己想要的效果(很多博客都是对word中的表格做操作,这很正常,NPOI的官方使用文档从头到尾的都是在讲对Excel的操作),于是乎自己摸索了一个。在这里觉得最最最重要的东西,不是写出来了,而是要学会去查看相关动态库的介绍、使用、开发文档,还有就是要学会用VS的对象浏览器,在这里可以找到自己想要的东西。比如在下面将要介绍的方法:

public void ReplaceText(string oldText, string newText);

通过对象浏览器看查看NPOI的相关组件找到了自己想要的方法,下面上代码。

1.首先的准备一个word模版,我的模版如图,这是一个国家两区规划的公示公告的文件模版(出于项目需要):

其中{$village} 为将要被替换掉的内容,是在程序读写中对word的中内容替换的关键字。

程序如下:

public struct PublicationInfor
{
    public string village;
    public string fullSite;
    public string area;
    public string deadLine;
    public string publicationTime;
}

class NPOIWriteToWord
{
    ///<summary>
    /// 测试村实测结果公示公告
    /// </summary>
    public static void WriteToPublicationOfResult()
    {
        FileStream fs = new FileStream(@"测试村实测结果公示公告.docx", FileMode.Open, FileAccess.Read);
        NPOI.XWPF.UserModel.XWPFDocument myDocx = new NPOI.XWPF.UserModel.XWPFDocument(fs);//打开07(.docx)以上的版本的文档
        PublicationInfor plcInfor = new PublicationInfor
        {
            village = "窝窝乡",
            fullSite = "神圣兽国游尾郡窝窝乡",
            area = "70.60",
            deadLine = "2018年12月12日",
            publicationTime = "2018年11月12日"
        };
        //遍历word中的段落
        foreach (var para in myDocx.Paragraphs)
        {
            string oldtext = para.ParagraphText;
            if (oldtext == "")
                continue;
            string temptext = para.ParagraphText;

            //以下为替换文档模版中的关键字
            if (temptext.Contains("{$village}"))
                temptext = temptext.Replace("{$village}", plcInfor.village);

            if (temptext.Contains("{$fullSite}"))
                temptext = temptext.Replace("{$fullSite}", plcInfor.fullSite);

            if (temptext.Contains("{$area}"))
                temptext = temptext.Replace("{$area}", plcInfor.area);

            if (temptext.Contains("{$deadLine}"))
                temptext = temptext.Replace("{$deadLine}", plcInfor.deadLine);

            if (temptext.Contains("{$publicationTime}"))
                temptext = temptext.Replace("{$publicationTime}", plcInfor.publicationTime);

            para.ReplaceText(oldtext, temptext);
        }

        FileStream output = new FileStream(@"测试村实测结果公示公告.docx", FileMode.Create);
        myDocx.Write(output);
        fs.Close();
        fs.Dispose();
        output.Close();
        output.Dispose();
    }
}

 

调用此方法后的执行结果:

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值