POI复制word、table、Paragraph
POI操作WORD,POI其实是很方便得,前提是找对方法。。。
首先把文件转成对象,方法为:
InputStream is = new FileInputStream(new File(FastLoan01main01title)); XWPFDocument doc = new XWPFDocument(is);
word的复制,从一个word复制到另一个word,方法为:
public static void copyDocument(XWPFDocument target, XWPFDocument source) { System.out.println("=====复制开始====="); //表格列表的index int tableIndex = 0; //段落列表的index int paragraphIndex = 0; for(IBodyElement body : source.getBodyElements()) { //如果元素是表格 if(body.getElementType() == BodyElementType.TABLE) { XWPFTable sourceTable = body.getBody().getTables(tableIndex++); XWPFTable targetTable = target.insertNewTbl(getBottomCurrsor(target)); cloneTable(targetTable, sourceTable); } //如果元素是段落 else if(body.getElementType() == BodyElementType.PARAGRAPH) { XWPFParagraph sourctParagraph = body.getBody().getParagraphArray(paragraphIndex++); XWPFParagraph targetParagraph = target.insertNewParagraph(getBottomCurrsor(target)); cloneParagraph(targetParagraph, sourctParagraph); } } System.out.println("=====复制结束====="); }
getBodyElements()可以获取word里面所有元素,包括段落和表格
复制段落和复制表格方法为:
public static void cloneTable(XWPFTable target, XWPFTable source) { target.getCTTbl().set(source.getCTTbl()); } public static void cloneParagraph(XWPFParagraph target, XWPFParagraph source) { target.getCTP().set(source.getCTP()); }
就这个方法,找了半天,原先查看API接口用下面的方法不可行,无法真正写入目标word
public void insertTable(int pos, XWPFTable table)//无实际效果
后面转变思路,先create一个空的table,再复制source进去,复制方法最终在stackoverflow上找到了,用的是CTP.set()
方法中还包括一个获取word最下面的游标位置,代码如下
public static XmlCursor getBottomCurrsor(XWPFDocument doc){ List<XWPFParagraph> paragraphList = doc.getParagraphs(); return paragraphList.get(paragraphList.size()-1).getCTP().newCursor(); }