首先要准备一个可读写的Word模板文件(.docx)或者什么都不需要,直接实例化一个XWPFDocument 空对象
FileStream fs = new FileStream(Application.StartupPath + "\\模板.docx", FileMode.OpenOrCreate, FileAccess.ReadWrite);//注意FileMode和FileAccess的搭配使用
XWPFDocument doc = new XWPFDocument(fs);//打开07(.docx)以上的版本的文档
//XWPFDocument doc = new XWPFDocument(); //创建新的word文档
然后向Word中插入文字段落或者表格
XWPFParagraph para1 = doc.CreateParagraph();
XWPFRun run1 = para1.CreateRun();
//设置文本的属性
run1.SetText("测试文本");
run1.FontSize=14;
run1.FontFamily = "仿宋";
run1.IsBold = true;
run1.SetUnderline(UnderlinePatterns.Single);
//插入空行
XWPFParagraph paranull = doc.CreateParagraph();
//插入分页符
para1.IsPageBreak = true;
//插入表格
List<XWPFTable> Tables = new List<XWPFTable>();
doc.CreateTable();//没插入一个table,都需要create一次
doc.SetTable(i, Tables[0]);//i为插入表格的索引顺序
//单独对表格新增
var oprTable = Tables[1];
XWPFTableRow m_Row=oprTable.InsertNewTableRow(1);//创建一行/并且在某个位置添加一行
m_Row.AddNewTableCell().SetText ("创建一行仅有一个单元格");
//XWPFTableRow m_Row2 = oprTable.InsertNewTableRow(2);//创建一行/并且在某个位置添加一行
m_Row2.AddNewTableCell().SetText("添加的新行");
//XWPFTableCell cellCt_P = m_Row2.CreateCell();//创建一个单元格,创建单元格时就创建了一个CT_P
//cellCt_P = m_Row2.CreateCell();
//cellCt_P = m_Row2.CreateCell();
单元格行和表
//CT_Tc cttc = cellCt_P.GetCTTc();
//CT_TcPr ctPr = cttc.AddNewTcPr();
ctPr.gridSpan.val = "3";//合并3列
//ctPr.AddNewVMerge().val = ST_Merge.restart;//合并行
//cellCt_P.SetText("创建一行仅有一个单元格(合并后)");
XWPFTableRow m_Row2 = oprTable.InsertNewTableRow(2);//创建一行/并且在某个位置添加一行
XWPFTableCell tc3 = m_Row2.CreateCell();//创建单元格
tc3.SetText("创建一行仅有一个单元格(合并后)");
CT_Tc ct3 = tc3.GetCTTc();
CT_TcPr cp3 = ct3.AddNewTcPr();
cp3.gridSpan = new CT_DecimalNumber();
cp3.gridSpan.val = "3"; //合并3列
XWPFTableRow m_Row3 = oprTable.InsertNewTableRow(2);//多个单元格以及合并
m_Row3.AddNewTableCell().SetText("添加的新行单元格1");
m_Row3.AddNewTableCell().SetText("添加的新行单元格2");
m_Row3.AddNewTableCell().SetText("添加的新行单元格3");
输出编辑后的Word
FileStream outFile = new FileStream(outPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
doc.Write(outFile);
outFile.Close();
doc.Close();