C#采用OpenXml實現(xiàn)給word文檔添加文字
本文實例講述了C#采用OpenXml實現(xiàn)給word文檔添加文字的方法,分享給大家供大家參考。具體方法如下:
一般來說,使用OpenXml給word文檔添加文字,每個模塊都有自己對于的屬性以及內(nèi)容,要設(shè)置樣式就先聲明屬性對象,將樣式Append到屬性里面,再將屬性append到模塊里面,那么模塊里面的內(nèi)容就具備該樣式了。此方法默認是在文件后面追加內(nèi)容
示例代碼如下:
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" }; // 設(shè)置字體 FontSize size = new FontSize() { Val = "52" }; // 設(shè)置字體大小 Color color = new Color() { Val = "red" }; // 設(shè)置字體樣式 // 將樣式添加到屬性里面 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#程序設(shè)計有所幫助。
相關(guān)文章
C#中參數(shù)數(shù)組、引用參數(shù)和輸出參數(shù)示例詳解
這篇文章主要給大家介紹了關(guān)于C#中參數(shù)數(shù)組、引用參數(shù)和輸出參數(shù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-05-05C#的path.GetFullPath 獲取上級目錄實現(xiàn)方法
這篇文章主要介紹了C#的path.GetFullPath 獲取上級目錄實現(xiàn)方法,包含了具體的C#實現(xiàn)方法以及ASP.net與ASP等的方法對比,非常具有實用價值,需要的朋友可以參考下2014-10-10舊項目升級新版Unity2021導致Visual?Studio無法使用的問題
在項目開發(fā)過程中,不可避免的會升級開發(fā)工具。這次我在舊項目版本升級到新版Unity2021.2.x時,出現(xiàn)Visual?Studio無法定位等問題,這里我給大家分享下解決方法,舊項目升級新版Unity2021導致Visual?Studio無法使用的問題,需要的朋友可以參考下2021-12-12