- NPOI
- Spire.Doc
- Download Sample Code
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NPOI
{
class Program
{
static void Main(string[] args)
{
//Create document
XWPFDocument doc = new XWPFDocument();
XWPFParagraph para=doc.CreateParagraph();
XWPFRun run = para.CreateRun();
run.SetText("Spire.Doc for .NET");
doc.Document.body.sectPr = new CT_SectPr();
CT_SectPr secPr = doc.Document.body.sectPr;
//Create header and set its text
CT_Hdr header = new CT_Hdr();
header.AddNewP().AddNewR().AddNewT().Value = "This is Header";
//Create footer and set its text
CT_Ftr footer = new CT_Ftr();
footer.AddNewP().AddNewR().AddNewT().Value = "This is Footer";
//Create the relation of header
XWPFRelation relation1 = XWPFRelation.HEADER;
XWPFHeader myHeader = (XWPFHeader)doc.CreateRelationship(relation1, XWPFFactory.GetInstance(), doc.HeaderList.Count + 1);
//Create the relation of footer
XWPFRelation relation2 = XWPFRelation.FOOTER;
XWPFFooter myFooter = (XWPFFooter)doc.CreateRelationship(relation2, XWPFFactory.GetInstance(), doc.FooterList.Count + 1);
//Set the header
myHeader.SetHeaderFooter(header);
CT_HdrFtrRef myHeaderRef = secPr.AddNewHeaderReference();
myHeaderRef.type = ST_HdrFtr.@default;
myHeaderRef.id = myHeader.GetPackageRelationship().Id;
//Set the footer
myFooter.SetHeaderFooter(footer);
CT_HdrFtrRef myFooterRef = secPr.AddNewFooterReference();
myFooterRef.type = ST_HdrFtr.@default;
myFooterRef.id = myFooter.GetPackageRelationship().Id;
//Save the file
using (FileStream stream = File.Create("HeaderAndFooter.docx"))
{
doc.Write(stream);
}
//Launch
System.Diagnostics.Process.Start("HeaderAndFooter.docx");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace Spire.Doc
{
class Program
{
static void Main(string[] args)
{
//Create document
Document doc = new Document();
Section section = doc.AddSection();
Paragraph para = section.AddParagraph();
para.AppendText("Spire.Doc for .NET");
//Add header
HeaderFooter header = section.HeadersFooters.Header;
Paragraph HParagraph = header.AddParagraph();
TextRange HText = HParagraph.AppendText("This is Header");
//Add footer
HeaderFooter footer = section.HeadersFooters.Footer;
Paragraph FParagraph = footer.AddParagraph();
TextRange FText = FParagraph.AppendText("This is Footer");
//Save and Launch
doc.SaveToFile("HeaderAndFooter.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("HeaderAndFooter.docx");
}
}
}
