1.下载poi相关libhttp://poi.apache.org/download.html
文件夹lib:doc功能实现依赖的包
文件夹:docx功能实现依赖的包
poi-4.1.2.jar :基础类
poi-scratchpad-4.0.0.jar:doc功能实现
poi-ooxml-4.1.2.jar ,poi-ooxml-schemas-4.1.2.jar :docx功能实现相关类
3.要实现根据docx导出docx表格数据需要导入poi-4.1.2.jar,poi-ooxml-4.1.2.jar, poi-ooxml-schemas-4.1.2.jar,dom4j-1.6.1.jar
stax-api-1.0.1.jar,xmlbeans-2.3.0.jar
4.配置word模板:将需要替换的单元格内容用${ } 替换
5.实现代码
try { // 配置需要替换的数据 Map<String, String> dataMap = new HashMap<String, String>(); dataMap.put("${1}","数据1"); dataMap.put("${2}", "数据2"); //打开word模板 InputStream inputStream = context.getAssets().open("模板.docx"); XWPFDocument document = new XWPFDocument(inputStream); //获取表格 Iterator<XWPFTable> it = document.getTablesIterator(); //表格内容替换添加 while (it.hasNext()) { XWPFTable table = it.next(); int rcount = table.getNumberOfRows(); for (int i = 0; i < rcount; i++) { XWPFTableRow row = table.getRow(i); List<XWPFTableCell> cells = row.getTableCells(); for (XWPFTableCell cell : cells) { //单元格 for (Map.Entry<String, String> e : dataMap.entrySet()) { if (cell.getText().trim().equals(e.getKey())) { //删除原来内容 cell.removeParagraph(0); //写入新内容 cell.setText((String) e.getValue()); } } } } } // 写入数据 (path:导出的文件路径) OutputStream os = new FileOutputStream(path); document.write(os); os.flush(); if (null != os) { os.close(); } if (null != inputStream) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); }