说明

最近工作被临时安排了一个给同事们报销的差事,要知道报销这个事情对于一个开发人员是真的麻烦透顶,数目金额等等都要核对。。。。想我一个根正苗红的正宗java开发工程师,是万万忍受不了让我一个个的填写信息的,所以就有了这篇文章。

那就开始吧

在这里我要吐槽一下,有些大神写完放上源码就完了,jar包版本也不说明,碰到jar包向下兼容的还好,有些jar包是完全大改,有的接口都不能用了!!所以还是希望写完博客的同时把背景交待清楚。。。

pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.sdut</groupId><artifactId>poiDemo</artifactId><version>1.0-SNAPSHOT</version><name>poiDemo</name><!-- FIXME change it to the project's website --><url>http://www.example.com</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.7</maven.compiler.source><maven.compiler.target>1.7</maven.compiler.target></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><!-- https://mvnrepository.com/artifact/commons-lang/commons-lang --><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.17</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas --><!--<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.17</version></dependency>--><!-- https://mvnrepository.com/artifact/org.apache.poi/ooxml-schemas --><dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.3</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-excelant</artifactId><version>3.17</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi-examples --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-examples</artifactId><version>3.17</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans --><dependency><groupId>org.apache.xmlbeans</groupId><artifactId>xmlbeans</artifactId><version>2.6.0</version></dependency><!-- https://mvnrepository.com/artifact/com.github.virtuald/curvesapi --><dependency><groupId>com.github.virtuald</groupId><artifactId>curvesapi</artifactId><version>1.04</version></dependency></dependencies><build><pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --><plugins><plugin><artifactId>maven-clean-plugin</artifactId><version>3.0.0</version></plugin><!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging --><plugin><artifactId>maven-resources-plugin</artifactId><version>3.0.2</version></plugin><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.7.0</version></plugin><plugin><artifactId>maven-surefire-plugin</artifactId><version>2.20.1</version></plugin><plugin><artifactId>maven-jar-plugin</artifactId><version>3.0.2</version></plugin><plugin><artifactId>maven-install-plugin</artifactId><version>2.5.2</version></plugin><plugin><artifactId>maven-deploy-plugin</artifactId><version>2.8.2</version></plugin></plugins></pluginManagement></build>
</project>
WordReporter.class
package com.sdut.PoiDemo;import org.apache.commons.lang.StringUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;import java.io.*;
import java.util.List;
import java.util.Map;/*** Created by lzx on 2018/8/12*/public class WordReporter {private String tempLocalPath;private XWPFDocument xwpfDocument = null;private FileInputStream inputStream = null;private OutputStream outputStream = null;public WordReporter(){}public WordReporter(String tempLocalPath){this.tempLocalPath = tempLocalPath;}/***  设置模板路径* @param tempLocalPath*/public void setTempLocalPath(String tempLocalPath) {this.tempLocalPath = tempLocalPath;}/***  初始化* @throws IOException*/public void init() throws IOException{inputStream = new FileInputStream(new File(this.tempLocalPath));xwpfDocument = new XWPFDocument(inputStream);}/***  导出方法* @param params* @param tableIndex* @return* @throws Exception*/public boolean export(List<Map<String,String>> params, int tableIndex) throws Exception{this.insertValueToTable(xwpfDocument,params,tableIndex);return true;}/*** 循环填充表格内容* @param xwpfDocument* @param params* @param tableIndex* @throws Exception*/private   void insertValueToTable(XWPFDocument xwpfDocument, List<Map<String,String>> params, int tableIndex) throws Exception {List<XWPFTable> tableList = xwpfDocument.getTables();if(tableList.size()<=tableIndex){throw new Exception("tableIndex对应的表格不存在");}XWPFTable table = tableList.get(tableIndex);List<XWPFTableRow> rows = table.getRows();if(rows.size()<2){throw new Exception("tableIndex对应表格应该为2行");}//模板的那一行XWPFTableRow tmpRow = rows.get(1);List<XWPFTableCell> tmpCells = null;List<XWPFTableCell> cells = null;XWPFTableCell tmpCell = null;tmpCells = tmpRow.getTableCells();String cellText = null;String cellTextKey = null;Map<String,Object> totalMap = null;for (int i = 0, len = params.size(); i < len; i++) {Map<String,String> map = params.get(i);// 创建新的一行XWPFTableRow row = table.createRow();// 获取模板的行高 设置为新一行的行高row.setHeight(tmpRow.getHeight());cells = row.getTableCells();for (int k = 0, klen = cells.size(); k < klen; k++) {tmpCell = tmpCells.get(k);XWPFTableCell cell = cells.get(k);cellText = tmpCell.getText();if (StringUtils.isNotBlank(cellText)) {//转换为mapkey对应的字段cellTextKey = cellText.replace("$", "").replace("{", "").replace("}", "");if (map.containsKey(cellTextKey)) {// 填充内容 并且复制模板行的属性setCellText(tmpCell,cell,map.get(cellTextKey));}}}}// 删除模版行table.removeRow(1);}/***  复制模板行的属性* @param tmpCell* @param cell* @param text* @throws Exception*/private void setCellText(XWPFTableCell tmpCell, XWPFTableCell cell,String text) throws Exception {CTTc cttc2 = tmpCell.getCTTc();CTTcPr ctPr2 = cttc2.getTcPr();CTTc cttc = cell.getCTTc();CTTcPr ctPr = cttc.addNewTcPr();if (ctPr2.getTcW() != null) {ctPr.addNewTcW().setW(ctPr2.getTcW().getW());}if (ctPr2.getVAlign() != null) {ctPr.addNewVAlign().setVal(ctPr2.getVAlign().getVal());}if (cttc2.getPList().size() > 0) {CTP ctp = cttc2.getPList().get(0);if (ctp.getPPr() != null) {if (ctp.getPPr().getJc() != null) {cttc.getPList().get(0).addNewPPr().addNewJc().setVal(ctp.getPPr().getJc().getVal());}}}if (ctPr2.getTcBorders() != null) {ctPr.setTcBorders(ctPr2.getTcBorders());}XWPFParagraph tmpP = tmpCell.getParagraphs().get(0);XWPFParagraph cellP = cell.getParagraphs().get(0);XWPFRun tmpR = null;if (tmpP.getRuns() != null && tmpP.getRuns().size() > 0) {tmpR = tmpP.getRuns().get(0);}XWPFRun cellR = cellP.createRun();cellR.setText(text);// 复制字体信息if (tmpR != null) {if(!cellR.isBold()){cellR.setBold(tmpR.isBold());}cellR.setItalic(tmpR.isItalic());cellR.setUnderline(tmpR.getUnderline());cellR.setColor(tmpR.getColor());cellR.setTextPosition(tmpR.getTextPosition());if (tmpR.getFontSize() != -1) {cellR.setFontSize(tmpR.getFontSize());}if (tmpR.getFontFamily() != null) {cellR.setFontFamily(tmpR.getFontFamily());}if (tmpR.getCTR() != null) {if (tmpR.getCTR().isSetRPr()) {CTRPr tmpRPr = tmpR.getCTR().getRPr();if (tmpRPr.isSetRFonts()) {CTFonts tmpFonts = tmpRPr.getRFonts();CTRPr cellRPr = cellR.getCTR().isSetRPr() ? cellR.getCTR().getRPr() : cellR.getCTR().addNewRPr();CTFonts cellFonts = cellRPr.isSetRFonts() ? cellRPr.getRFonts() : cellRPr.addNewRFonts();cellFonts.setAscii(tmpFonts.getAscii());cellFonts.setAsciiTheme(tmpFonts.getAsciiTheme());cellFonts.setCs(tmpFonts.getCs());cellFonts.setCstheme(tmpFonts.getCstheme());cellFonts.setEastAsia(tmpFonts.getEastAsia());cellFonts.setEastAsiaTheme(tmpFonts.getEastAsiaTheme());cellFonts.setHAnsi(tmpFonts.getHAnsi());cellFonts.setHAnsiTheme(tmpFonts.getHAnsiTheme());}}}}// 复制段落信息cellP.setAlignment(tmpP.getAlignment());cellP.setVerticalAlignment(tmpP.getVerticalAlignment());cellP.setBorderBetween(tmpP.getBorderBetween());cellP.setBorderBottom(tmpP.getBorderBottom());cellP.setBorderLeft(tmpP.getBorderLeft());cellP.setBorderRight(tmpP.getBorderRight());cellP.setBorderTop(tmpP.getBorderTop());cellP.setPageBreak(tmpP.isPageBreak());if (tmpP.getCTP() != null) {if (tmpP.getCTP().getPPr() != null) {CTPPr tmpPPr = tmpP.getCTP().getPPr();CTPPr cellPPr = cellP.getCTP().getPPr() != null ? cellP.getCTP().getPPr() : cellP.getCTP().addNewPPr();// 复制段落间距信息CTSpacing tmpSpacing = tmpPPr.getSpacing();if (tmpSpacing != null) {CTSpacing cellSpacing = cellPPr.getSpacing() != null ? cellPPr.getSpacing() : cellPPr.addNewSpacing();if (tmpSpacing.getAfter() != null) {cellSpacing.setAfter(tmpSpacing.getAfter());}if (tmpSpacing.getAfterAutospacing() != null) {cellSpacing.setAfterAutospacing(tmpSpacing.getAfterAutospacing());}if (tmpSpacing.getAfterLines() != null) {cellSpacing.setAfterLines(tmpSpacing.getAfterLines());}if (tmpSpacing.getBefore() != null) {cellSpacing.setBefore(tmpSpacing.getBefore());}if (tmpSpacing.getBeforeAutospacing() != null) {cellSpacing.setBeforeAutospacing(tmpSpacing.getBeforeAutospacing());}if (tmpSpacing.getBeforeLines() != null) {cellSpacing.setBeforeLines(tmpSpacing.getBeforeLines());}if (tmpSpacing.getLine() != null) {cellSpacing.setLine(tmpSpacing.getLine());}if (tmpSpacing.getLineRule() != null) {cellSpacing.setLineRule(tmpSpacing.getLineRule());}}// 复制段落缩进信息CTInd tmpInd = tmpPPr.getInd();if (tmpInd != null) {CTInd cellInd = cellPPr.getInd() != null ? cellPPr.getInd(): cellPPr.addNewInd();if (tmpInd.getFirstLine() != null) {cellInd.setFirstLine(tmpInd.getFirstLine());}if (tmpInd.getFirstLineChars() != null) {cellInd.setFirstLineChars(tmpInd.getFirstLineChars());}if (tmpInd.getHanging() != null) {cellInd.setHanging(tmpInd.getHanging());}if (tmpInd.getHangingChars() != null) {cellInd.setHangingChars(tmpInd.getHangingChars());}if (tmpInd.getLeft() != null) {cellInd.setLeft(tmpInd.getLeft());}if (tmpInd.getLeftChars() != null) {cellInd.setLeftChars(tmpInd.getLeftChars());}if (tmpInd.getRight() != null) {cellInd.setRight(tmpInd.getRight());}if (tmpInd.getRightChars() != null) {cellInd.setRightChars(tmpInd.getRightChars());}}}}}/***  收尾方法* @param outDocPath* @return* @throws IOException*/public boolean generate(String outDocPath) throws IOException{outputStream = new FileOutputStream(outDocPath);xwpfDocument.write(outputStream);this.close(outputStream);this.close(inputStream);return true;}/***  关闭输入流* @param is*/private void close(InputStream is) {if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}}/***  关闭输出流* @param os*/private void close(OutputStream os) {if (os != null) {try {os.close();} catch (IOException e) {e.printStackTrace();}}}}
WordExportDemo.class
package com.sdut.PoiDemo;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** Created by lzx on 2018/8/12*/public class WordExportDemo {public static void main(String[] args) throws Exception {// 添加假数据 这里你也可以从数据库里获取数据List<Map<String, String>> list = new ArrayList<>();for (int i =0;i < 30; i++){Map<String,String> map = new HashMap<>();map.put("time", "2018"+i);map.put("begin", "我在这"+i);map.put("end", "你好"+i);map.put("content", "加班啊"+i);map.put("money", "123");list.add(map);}// 模板文件输入输出地址String filePath = "E:/workspace/poiDemo/src/main/java/config/demo.docx";String outPath = "E:/workspace/poiDemo/src/main/java/config/demo1.docx";WordReporter wordReporter = new WordReporter();wordReporter.setTempLocalPath(filePath);wordReporter.init();wordReporter.export(list,0);wordReporter.generate(outPath);}
}
模板文件地址

截图展示

模板文件

最终结果

demo.docx 就是模板文件
参考博客:https://blog.csdn.net/zsq520520/article/details/53538301
项目源码地址下载:https://download.csdn.net/download/sdut406/10599534

POI使用word模板文件循环输出行并导出word相关推荐

  1. 基于POI的wod模板文件,导入参数,导出最终文件

    最近工作上碰到了这个问题,就研究了一下. 结合了网上几位大哥的成果,我自己又优化了一下. 除了基础的导入参数之外,还优化了参数识别能力,添加了页面复制能力,并且保留了样式. 下面是我测试的word模板 ...

  2. 利用poi读取word模板文件生成新的word文档

    利用poi读取word模板文件生成新的word文档 利用poi读取word模板文件,并回填逻辑数据,生成并导出需要的word文档源码.解决模板读取异常问题,提供wordUtils工具类(各种功能实现) ...

  3. java word模板poi生成文件_利用poi读取word模板文件生成新的word文档

    利用poi读取word模板文件生成新的word文档 利用poi读取word模板文件,并回填逻辑数据,生成并导出需要的word文档源码.解决模板读取异常问题,提供wordUtils工具类(各种功能实现) ...

  4. Aspose-words结合Freemarker实现word邮件合并功能,批量处理word模板文件

    最近的工作中有一个需求,需要处理word文档,有一些内容需要根据不同用户进行替换修改,使用的是word文档,替换后的内容还需要转换为pdf进行签章确认,并进行防篡改处理. 所以记录一下处理步骤,首先可 ...

  5. java 文件 模板 替换_JAVA 处理Word模板文件,替换其中的占位符

    1.java处理word是个大大的坑,无论是poi还是Java2word 都不是尽善尽美. 2.poi只能进行简单读操作,Java2word需要调用系统的com接口,系统机必须安装office和动态链 ...

  6. java实现word模板文件填充

    核心 import org.docx4j.openpackaging.packages.WordprocessingMLPackage; 使用该包实现 word 文件填充,同时支持 pdf.excel ...

  7. C#操作Word模板文件 替换并重新生成

    啥也不说,直接上干货! 我自己用的 IDE 环境是 VS 2019 示例代码结构:(超简单) 这里用到了一个操作 Word 的第三方开源库:DocX:这个库对于操作 Word 文件绝对是个好东西,更优 ...

  8. 使用NPOI按照word模板文件生成新的word文件

    /// <summary>/// 按照word模板文件 生成新word文件/// </summary>/// <param name="tempFile&quo ...

  9. Csharp 简单操作Word模板文件

    1.创建一个模板的Word文档  Doc1.dot 内容为: To: <Name> Sub:<Subject> Website is ok geovindu 涂聚文好样的 wo ...

最新文章

  1. 鸿蒙系统tee内核,厉害!鸿蒙内核的技术定位,是赶第三代微内核的潮流
  2. Linux下遍历指定目录的C++实现
  3. 阿里云发布第四代神龙架构云计算首次进入5微秒时延时代
  4. 《强化学习周刊》第2期:多智能体强化学习(MARL)赋能“AI智能时代”
  5. Android 使用jtds远程访问数据库
  6. 观察者模式--java jdk中提供的支持
  7. 期待!华为或在今年8月/9月推出自家操作系统
  8. find的详细用法及其例子
  9. linux 进程的pid分配策略——pid位图算法
  10. Simple QQLogin 1.3(QQ2008 或更早版本)
  11. vue的npm run dev做了什么
  12. 科学计算机求n次方,科学计算器怎么算n次方_科学计算器的度分秒怎么按
  13. 基于android的理财软件,基于Android的理财系统APP的设计
  14. 【翻译】LearnYouSomeErlangForGreatGood(一):导言
  15. 开发者账号注册的详细流程
  16. Update|亚洲精品菜订餐平台「Chowbus」获400万美金新融资,由Greycroft和FJ labs领投...
  17. Tokio教程之select
  18. Oracle bpm实现oa,Oracle BPM/SOA API 操作流程
  19. shuffle什么意思?python模拟随机发牌(斗地主、掼蛋)
  20. GBase 8a集群目录结构

热门文章

  1. Hologres 助力飞猪双11实时数据大屏秒级响应
  2. 19-Linux计划任务
  3. web前端开发远程调试工具Weinre
  4. Qt:Qt Widgets
  5. matlab 三维相交面,MATLAB画三维图时如何画相交部分
  6. LTE----013 UE开机后的第一件事: PLMN选择
  7. 费马小定理以及快速幂应用
  8. 计算机能显示u盘吗,U盘插到电脑上,能检测到这设备,但是在“我的电脑”里没有显示U盘...
  9. 解决uni-app微信小程序底部input输入框,键盘弹起时页面整体上移问题
  10. 【踩坑】Rock5B测试USB摄像头和安装OpenCV