java openxml word_C#采用OpenXml实现给word文档添加文字

本文实例讲述了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();

}

}

}

}

运行效果截图如下:

eb0d6cb71069e1781f38aa0a5822a3a8.png

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值