admin 管理员组文章数量: 887007
注意:这是简单实现,主要是对table,段落的实现,图片的拷贝,sdt的拷贝会在之后的文档中实现
<dependency> <groupId>com.deepoove</groupId> <artifactId>poi-tl</artifactId> <version>1.12.1</version> </dependency>
import org.apachemons.collections4.CollectionUtils; import org.apachemons.lang3.StringUtils; import org.apache.poi.xwpf.usermodel.*; import java.io.*; import java.util.ArrayList; import java.util.List; public class WriteOutWord { private static String def_path = "自己路劲"+System.currentTimeMillis()+".docx"; public static void writeElementOut(List<IBodyElement> bodyElements,String path) { XWPFDocument newDoc = generateNewXWPFDoc(bodyElements); if(StringUtils.isBlank(path)){ path = def_path; } writeOutFile(newDoc,path); }
/** * 生成新的XWPFDocument对象 * @param bodyElements * @return */ private static XWPFDocument generateNewXWPFDoc(List<IBodyElement> bodyElements) { XWPFDocument newDoc = new XWPFDocument(); for (int i = 0; i < bodyElements.size(); i++) { IBodyElement bodyElement = bodyElements.get(i); elementFitAndSet(newDoc,bodyElement); } return newDoc; } /** * 匹配文本类型 * @param newDoc * @param bodyElement */ private static void elementFitAndSet(XWPFDocument newDoc,IBodyElement bodyElement){ if(bodyElement instanceof XWPFParagraph){ copyParagraph(newDoc,bodyElement); }else if(bodyElement instanceof XWPFTable){ setTable(newDoc,bodyElement); }else { throw new RuntimeException("其余文本类型,还需要扩展"); } } /** * copy 段落组件 * @param newDoc * @param bodyElement */ private static void copyParagraph(XWPFDocument newDoc,IBodyElement bodyElement){ XWPFParagraph paragraph = (XWPFParagraph)bodyElement; int paragraphIndex = getParagraphIndex(newDoc); newDoc.createParagraph(); newDoc.setParagraph(paragraph,paragraphIndex); } /** * 获取段落组件的index值 * @param newDoc * @return */ private static int getParagraphIndex(XWPFDocument newDoc){ List<XWPFParagraph> paragraphs = newDoc.getParagraphs(); if(CollectionUtils.isEmpty(paragraphs)){ return 0; } return paragraphs.size(); } /** * copy 表格组件 * @param newDoc * @param bodyElement */ private static void setTable(XWPFDocument newDoc,IBodyElement bodyElement){ XWPFTable table = (XWPFTable)bodyElement; int tableIndex = getTableIndex(newDoc); newDoc.createTable(); newDoc.setTable(tableIndex,table); } /** * 获取表格组件的index值 * @param newDoc * @return */ private static int getTableIndex(XWPFDocument newDoc){ List<XWPFTable> tables = newDoc.getTables(); if(CollectionUtils.isEmpty(tables)){ return 0; } return tables.size(); } /** * docx 写出到本地 * @param newDoc * @param path */ public static void writeOutFile(XWPFDocument newDoc,String path){ try { FileOutputStream out = new FileOutputStream(path); newDoc.write(out); }catch (IOException e){ } }
}
版权声明:本文标题:poi - 拷贝部分内容到其他word文件 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/jishu/1727635299h1143283.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论