C#采用OpenXml實現(xiàn)給word文檔添加文字
更新時間:2014年09月24日 10:19:50 投稿:shichen2014
這篇文章主要介紹了C#采用OpenXml實現(xiàn)給word文檔添加文字的方法,包括了用法的實例分析,是非常實用的技巧,需要的朋友可以參考下
本文實例講述了C#采用OpenXml實現(xiàn)給word文檔添加文字的方法,分享給大家供大家參考。具體方法如下:
一般來說,使用OpenXml給word文檔添加文字,每個模塊都有自己對于的屬性以及內(nèi)容,要設(shè)置樣式就先聲明屬性對象,將樣式Append到屬性里面,再將屬性append到模塊里面,那么模塊里面的內(nèi)容就具備該樣式了。此方法默認(rèn)是在文件后面追加內(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#連續(xù)任務(wù)Task.ContinueWith方法
這篇文章介紹了C#中的連續(xù)任務(wù)Task.ContinueWith方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04
C#數(shù)據(jù)結(jié)構(gòu)之循環(huán)鏈表的實例代碼
C#數(shù)據(jù)結(jié)構(gòu)之循環(huán)鏈表的實例代碼,需要的朋友可以參考一下2013-03-03
UnityShader3實現(xiàn)轉(zhuǎn)圈與冷卻效果
這篇文章主要為大家詳細介紹了UnityShader3實現(xiàn)轉(zhuǎn)圈與冷卻效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-03-03

