Java使用Aspose处理word中的段落字体格式、内容、批注、表格,比poi方便很多:
public static void main(String[] args) throws Exception{
//initLicence(); //初始化证书,自己想办法解决,Aspose是一个付费服务,jar包未配置证书的情况下处理文档会有水印
Document document = new Document("D:\\test.docx");
for(Section section: document.getSections()){
NodeCollection collection = section.getBody().getChildNodes();
for(int i=0;i<collection.getCount();i++){
if(collection.get(i).getNodeType()== NodeType.PARAGRAPH){ //word中的段落
Paragraph paragraph = (Paragraph)collection.get(i);
String content = paragraph.getText(); // 段落文本内容
String styleName = paragraph.getParagraphFormat().getStyle().getName(); //段落样式名称
Font phFont = paragraph.getParagraphFormat().getStyle().getFont(); //段落级别的font
paragraph.getParagraphFormat().getAlignment(); //0-left 1-center 2-right 3-两头对齐
paragraph.getRuns().add(new Run(document,"")); //段落末尾添加字符
for (Run run : paragraph.getRuns()) {
run.setText(run.getText()+""); //设置run的内容,此举会替换原有的run的内容 格式和原来的run一致
Font font = run.getFont();
font.getShading().setBackgroundPatternColor(Color.RED); //run级别的设置背景色
font.getName(); //字体名
font.getSize(); //字体大小
font.setSize(10.5); //设置字体大小,其他的属性都是这种做法,不写了
Comment comment = new Comment(document,"auth","",new Date()); //批注
comment.getParagraphs().add(new Paragraph(document));
comment.getFirstParagraph().getRuns().add(new Run(document,"批注内容"));
run.getParentNode().insertAfter(comment,run); //给这个run设置批注,给一整个段落设置批注也是类似的做法
}
if(paragraph.isListItem()){
System.out.println("列表标题段落--");
}
}else if(collection.get(i).getNodeType()==NodeType.TABLE){ //word中的table
Table table = (Table)collection.get(i);
for(Row row:table.getRows()){
for(Cell cell: row.getCells()){
cell.getParagraphs(); //获取表格cell中的段落,段落处理方式和上面的一样
}
}
}else{
//还有其他类型的Node,比如批注类型NodeType.COMMENT,不写了
}
}
}
document.save("D:\\target.docx"); //修改后的word最终保存的位置
}
以上内容都可以在Aspose官网API中找到。