OpenXml入门----给Word文档添加文字


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

Code:

 

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();
            }
        }
    }
}

 截图如下:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM