当前位置: 移动技术网 > IT编程>开发语言>c# > C#采用OpenXml实现给word文档添加文字

C#采用OpenXml实现给word文档添加文字

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了c#采用openxml实现给word文档添加文字的方法,分享给大家供大家参考。具体方法如下:

一般来说,使用openxml给word文档添加文字,每个模块都有自己对于的属性以及内容,要设置样式就先声明属性对象,将样式append到属性里面,再将属性append到模块里面,那么模块里面的内容就具备该样式了。此方法默认是在文件后面追加内容

示例代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;
using documentformat.openxml;
using documentformat.openxml.packaging;
using documentformat.openxml.wordprocessing;
 
namespace addstringtoword
{
  public class program
  {
    public static void main(string[] args)
    {
      addstring("test.docx", "你好呀");
    }
 
    public static void addstring(string filepath, string str)
    {
      using (wordprocessingdocument doc = wordprocessingdocument.open(filepath, true))
      {
        paragraph paragraph = new paragraph();
        run run = new run();
 
        runproperties runproperties = new runproperties(); //属性
 
        runfonts fonts = new runfonts() { eastasia = "dfkai-sb" }; // 设置字体
        fontsize size = new fontsize() { val = "52" }; // 设置字体大小
        color color = new color() { val = "red" }; // 设置字体样式
 
        // 将样式添加到属性里面
        runproperties.append(color);
        runproperties.append(size);
        runproperties.append(fonts);
 
        run.append(runproperties);
        run.append(new text(str));
        paragraph.append(run);
        doc.maindocumentpart.document.body.append(paragraph);
        doc.maindocumentpart.document.save();
      }
    }
  }
}

运行效果截图如下:

希望本文所述对大家的c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网