操作 word 文档
/**
* 去掉文档表格,并插入指定格式的文字以及表格
* @throws Exception
*/
public static void test1() throws Exception {
FileInputStream inputStream = new FileInputStream("E:\\测试文档.docx");
Document document = new Document(inputStream);
// 去掉表格
NodeCollection allNode = document.getChildNodes(NodeType.TABLE, true);
for(int i = 0; i < allNode.getCount(); i++) {
Node node = allNode.get(i);
node.remove();
}
// 获取所有的段落
ParagraphCollection paras = document.getFirstSection().getBody().getParagraphs();
DocumentBuilder builder = new DocumentBuilder(document);
// 在所有段落之前添加一个新的段落
Paragraph newPara2 = new Paragraph(document);
// 设置新段落的样式
newPara2.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
newPara2.getParagraphFormat().setSpaceAfter(5);
// 插入新的段落
paras.insert(0,newPara2);
Paragraph firstPara2 = paras.get(0);
// 移动到新的段落,设置段落的字体样式,并添加文字
builder.moveTo(firstPara2);
Font font2 = builder.getFont();
font2.setSize(16);
font2.setName("仿宋_GB2312");
builder.write("\r\n 这是新段落1");
// 插入表格
// 移动到第二个段落
Paragraph firstPara = document.getFirstSection().getBody().getParagraphs().get(1);
builder.moveTo(firstPara);
// 插入新的表格
Table table = builder.startTable();
// 插入单元格
builder.insertCell();
// 设置表格样式
table.setAlignment(CellVerticalAlignment.CENTER);
table.setPreferredWidth(PreferredWidth.fromPercent(97));
// 设置单元格样式
Border topBorder = builder.getCellFormat().getBorders().getTop();
topBorder.setColor(Color.RED);
topBorder.setLineWidth(2.25);
builder.getCellFormat().getBorders().getLeft().setLineStyle(LineStyle.NONE);
builder.getCellFormat().getBorders().getRight().setLineStyle(LineStyle.NONE);
builder.getCellFormat().getBorders().getBottom().setLineStyle(LineStyle.NONE);
builder.endTable();
// 删除多余的空行段落
document.getFirstSection().getBody().getParagraphs().removeAt(2);
// 在文档开头再加一个新段落
paras = document.getFirstSection().getBody().getParagraphs();
Paragraph newPara3 = new Paragraph(document);
newPara3.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
paras.insert(0,newPara3);
Paragraph firstPara3 = paras.get(0);
builder.moveTo(firstPara3);
final Font font3 = builder.getFont();
font3.setSize(65);
font3.setColor(Color.red);
font3.setName("方正小标宋简体");
font3.setScaling(80);
font3.setSpacing(-2);
builder.write("这是新段落2");
document.save("E:\\测试文档");
}