C#采用OpenXml實(shí)現(xiàn)給word文檔添加文字
本文實(shí)例講述了C#采用OpenXml實(shí)現(xiàn)給word文檔添加文字的方法,分享給大家供大家參考。具體方法如下:
一般來(lái)說(shuō),使用OpenXml給word文檔添加文字,每個(gè)模塊都有自己對(duì)于的屬性以及內(nèi)容,要設(shè)置樣式就先聲明屬性對(duì)象,將樣式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();
}
}
}
}
運(yùn)行效果截圖如下:

希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
C#入門(mén)之定義類(lèi)成員與接口實(shí)現(xiàn)
這篇文章介紹了C#入門(mén)之定義類(lèi)成員與接口實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-05-05
客戶端實(shí)現(xiàn)藍(lán)牙接收(C#)知識(shí)總結(jié)
網(wǎng)上有關(guān)藍(lán)牙接收的資料很多,使用起來(lái)也很簡(jiǎn)單,但是我覺(jué)得還是有必要把這些知識(shí)總結(jié)下來(lái),藍(lán)牙開(kāi)發(fā)需要用到一個(gè)第三方的庫(kù)InTheHand.Net.Personal.dll,感興趣的朋友可以了解下,或許對(duì)你有所幫助2013-02-02
C#連續(xù)任務(wù)Task.ContinueWith方法
這篇文章介紹了C#中的連續(xù)任務(wù)Task.ContinueWith方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-04-04
C#數(shù)據(jù)結(jié)構(gòu)之循環(huán)鏈表的實(shí)例代碼
C#數(shù)據(jù)結(jié)構(gòu)之循環(huán)鏈表的實(shí)例代碼,需要的朋友可以參考一下2013-03-03
UnityShader3實(shí)現(xiàn)轉(zhuǎn)圈與冷卻效果
這篇文章主要為大家詳細(xì)介紹了UnityShader3實(shí)現(xiàn)轉(zhuǎn)圈與冷卻效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-03-03

