1.总体说明:操作主要涉及两个对象Document及DocumentBuilder
Document主要用来获取文档中的节点,DocumentBuilder主要用于实现文档内容的写入
doc_Operate = new Document(blankTemplatePth); doc_template = new Document(ToCopytemplatePth); builder_template = new DocumentBuilder(doc_template); builder_operate = new DocumentBuilder(doc_Operate);
2.内容写入,样式设置
builder_operate.ParagraphFormat.Style = doc_Operate.Styles["标题"]; builder_operate.Writeln("XXX报告"); builder_operate.ParagraphFormat.Style = doc_Operate.Styles["正文"]; builder_operate.Writeln("(征求意见稿)");
3.关于分节,分节之后,需要将当前插入光标移动至新插入的Section中,否则容易出错
builder_operate.InsertBreak(BreakType.SectionBreakNewPage); Section lstSection2 = doc_Operate.LastSection; int idx2 = doc_Operate.Sections.IndexOf(lstSection2); builder_operate.MoveToSection(idx2); builder_operate.MoveToDocumentEnd();
4.复制模板文档中的表格,插入到当前文档中
//获取Table对象
Table tbN=doc.ImportNode(tb, true, ImportFormatMode.KeepSourceFormatting) as Table; doc.LastSection.Body.AppendChild(tbN); Paragraph p = new Paragraph(doc); tbN.ParentNode.AppendChild(p); //添加paragraph,以打断表格
5.当前表格插入新行
Row rN = table_N.Rows[1].Clone(true) as Row; table_N.InsertAfter(rN, table_N.LastRow);
6.单元格插入图片
builder_operate.MoveToCell(tableindex, 0, 0, 0); Aspose.Words.Drawing.Shape spa = builder_operate.InsertImage(jietuA);
此处插入图片时,容易出现异常,提示tableindex超出索引,TableIndex是通过indexOf对象获取到的.
查阅大量资料发现,如果一个word文档中出现了多个Section,需要采用本篇第3小节的内容,移动当前的光标
7.设置单元格内容