在使用 C# 編程操作 Apache POI XWPFDocument(Word 文檔)時,可以通過以下步驟應(yīng)用模板和樣式:
using System.IO;
using NPOI.XWPF.UserModel;
// 打開現(xiàn)有的模板文檔
using FileStream fs = new FileStream("template.docx", FileMode.Open, FileAccess.Read);
XWPFDocument templateDoc = new XWPFDocument(fs);
// 創(chuàng)建一個新文檔
XWPFDocument newDoc = new XWPFDocument();
// 復制模板文檔的內(nèi)容到新文檔
foreach (var para in templateDoc.Paragraphs)
{
XWPFParagraph newPara = newDoc.CreateParagraph();
newPara.Alignment = para.Alignment;
newPara.FirstLineIndent = para.FirstLineIndent;
foreach (var run in para.Runs)
{
XWPFRun newRun = newPara.CreateRun();
newRun.IsBold = run.IsBold;
newRun.SetText(run.Text);
}
}
可以通過設(shè)置段落和運行對象的屬性來應(yīng)用樣式,例如字體、顏色、對齊方式等。
XWPFParagraph para = newDoc.CreateParagraph();
XWPFRun run = para.CreateRun();
run.SetText("This is a styled text.");
run.IsBold = true;
run.FontSize = 12;
run.FontFamily = "Arial";
run.SetTextHighlightColor(XWPFHighlightColor.Yellow);
para.Alignment = ParagraphAlignment.CENTER;
最后,將保存新文檔:
using (FileStream fs = new FileStream("output.docx", FileMode.Create, FileAccess.Write))
{
newDoc.Write(fs);
}
通過這些步驟,您可以在 C# 中應(yīng)用模板和樣式來創(chuàng)建自定義的 Word 文檔。