<!-- 需要用的包-->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.14</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.14</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.14</version>
</dependency>
package com.example.demo.jisuan;import org.apache.poi.POIXMLDocument;import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.List;public class WordUtil2 {/*** 替换word中指定字符串* 注意模板需要替换的字符串的格式* 1、要连着打出来,或者在别的地方写好粘过来* 2、先word转PDF,再将PDF转word* <p>* 替换word模板并生成新的word** @param srcPath  模板地址* @param destPath 新的word地址* @param map      替换的内容* @return 是否成功替换*/public static boolean newWord(String srcPath,String destPath, Map<String, Object> map) {//创建新的word文件File errorExcelfile = new File(destPath);if (!errorExcelfile.exists()) {File file = errorExcelfile.getParentFile();if (!file.exists())file.mkdirs();}try {OPCPackage opcPackage = POIXMLDocument.openPackage(srcPath);CustomXWPFDocument doc = new CustomXWPFDocument(opcPackage);// 替换段落中的指定文字Iterator<XWPFParagraph> itPara = doc.getParagraphsIterator();while (itPara.hasNext()) {XWPFParagraph paragraph = (XWPFParagraph) itPara.next();List<XWPFRun> runs = paragraph.getRuns();for (int i = 0; i < runs.size(); i++) {//遍历读取模板的内容String oneparaString = runs.get(i).getText(runs.get(i).getTextPosition());if (oneparaString == null) {continue;}//遍历要替换的内容  和模板相同字符串的key 被替换为valuefor (Map.Entry<String, Object> entry : map.entrySet()) {String key = entry.getKey();if (oneparaString.indexOf(key) != -1) {Object value = entry.getValue();if (value instanceof String) {oneparaString = oneparaString.replace(entry.getKey(), entry.getValue().toString());} else if (value instanceof Map) {//判断如果值是map类型 就说明是图片oneparaString = oneparaString.replace(key, "");Map pic = (Map) value;int width = Integer.parseInt(pic.get("width").toString());int height = Integer.parseInt(pic.get("height").toString());int picType = getPictureType(pic.get("type").toString());byte[] byteArray = (byte[]) pic.get("content");ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);//以字节流的形式 向  XWPFParagraph 添加图片doc.addPictureData(byteInputStream, picType);//创建图片模板doc.createPicture(doc.getAllPictures().size() - 1, width, height, paragraph);}}}runs.get(i).setText(oneparaString, 0);}}FileOutputStream outStream = null;outStream = new FileOutputStream(destPath);doc.write(outStream);outStream.close();return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 根据图片类型,取得对应的图片类型代码** @param picType* @return int*/private static int getPictureType(String picType) {int res = CustomXWPFDocument.PICTURE_TYPE_PICT;if (picType != null) {if (picType.equalsIgnoreCase("png")) {res = CustomXWPFDocument.PICTURE_TYPE_PNG;} else if (picType.equalsIgnoreCase("dib")) {res = CustomXWPFDocument.PICTURE_TYPE_DIB;} else if (picType.equalsIgnoreCase("emf")) {res = CustomXWPFDocument.PICTURE_TYPE_EMF;} else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {res = CustomXWPFDocument.PICTURE_TYPE_JPEG;} else if (picType.equalsIgnoreCase("wmf")) {res = CustomXWPFDocument.PICTURE_TYPE_WMF;}}return res;}public static void main(String[] args) {System.out.println("hello world");List<Person> dtos = new ArrayList<>();for (int i = 0; i < 20; i++) {Person dto = new Person();if(i%3==0){dto.setName("张三" + i);dto.setSex("nan" + i);dto.setAge("11" + i);dtos.add(dto);}else{dto.setName("");dto.setSex("nan" + i);dto.setAge("");dtos.add(dto);}}List<String> head = new ArrayList<>();head.add("姓名");head.add("年龄");head.add("性别");String srcPath = "F:\\jinxin.docx";String targetPath = "F:\\jinxin1.docx";String key = "liebiaotable";// 在文档中需要替换插入表格的位置exportBg(head, dtos, srcPath, targetPath, key);}//    public static void main(String[] args) {
//        Map<String,Object> map = new HashMap<>();
//        map.put("需求说明","测试替换");
//        newWord("F:\\jin.docx","F:\\jinxin.docx",map);
//    }/*** 替换word中指定字符串(这里用来将字符串替换为表格,上边的newWord用来替换文字等)* @param head 表头* @param data 数据* @param srcPath 需要操作的文档模板* @param targetPath 操作完后输出的位置* @param key 需要替换的文字,如果需要替换多个位置就用个map啥的* @param <T>*///创建一个表格插入到key标记的位置public static <T> void exportBg(List<String> head, List<T> data, String srcPath, String targetPath, String key) {XWPFDocument doc = null;try {doc = new XWPFDocument(POIXMLDocument.openPackage(srcPath));List<XWPFParagraph> paragraphList = doc.getParagraphs();if (paragraphList != null && paragraphList.size() > 0) {for (XWPFParagraph paragraph : paragraphList) {List<XWPFRun> runs = paragraph.getRuns();for (int i = 0; i < runs.size(); i++) {String text = runs.get(i).getText(0);if (text != null) {text = text.trim();if (text.indexOf(key) >= 0) {runs.get(i).setText(text.replace(key, ""), 0);XmlCursor cursor = paragraph.getCTP().newCursor();// 在指定游标位置插入表格XWPFTable table = doc.insertNewTbl(cursor);CTTblPr tablePr = table.getCTTbl().getTblPr();CTTblWidth width = tablePr.addNewTblW();//获取这个东西用来改表格宽度width.setW(BigInteger.valueOf(7000));insertInfo(table, head, data);break;}}}}}FileOutputStream os = new FileOutputStream(targetPath);doc.write(os);os.flush();os.close();} catch (IOException | IllegalAccessException | IntrospectionException | InvocationTargetException e) {e.printStackTrace();}}/*** 把信息插入表格*/private static <T> void insertInfo(XWPFTable table, List<String> head, List<T> data) throws IntrospectionException, InvocationTargetException, IllegalAccessException {//获取第一行XWPFTableRow row = table.getRow(0);
//        //获取这个东西用来改表格宽度
//        CTTblPr tblPr = table.getCTTbl().getTblPr();
//        //改变长度策略为自己调整 默认为auto
//        tblPr.getTblW().setType(STTblWidth.DXA);
//        //设置表格宽度为7000
//        tblPr.getTblW().setW(BigInteger.valueOf(10));//根据头创建表格headfor (int col = 1; col < head.size(); col++) {//默认会创建一列,即从第2列开始// 第一行创建了多少列,后续增加的行自动增加列CTTcPr cPr = row.createCell().getCTTc().addNewTcPr();//设置单元格高度为500row.getCtRow().addNewTrPr().addNewTrHeight().setVal(BigInteger.valueOf(500));//可以用来设置单元格长度//CTTblWidth width = cPr.addNewTcW();//width.setW(BigInteger.valueOf(2000));}//循环给表格添加头信息for (int i = 0; i < head.size(); i++) {//往表格里面写入头信息row.getCell(i).setText(head.get(i));}//计数器int i = 0;//循环填充body列表(列表为vo数组)for (T item : data) {//获取类Class<?> clazz = item.getClass();//获取item字段Field[] fields = item.getClass().getDeclaredFields();//创建行row = table.createRow();//修改行高为500row.getCtRow().addNewTrPr().addNewTrHeight().setVal(BigInteger.valueOf(1000));//循环获取vo类的属性for (Field field : fields) {//获取当前field的属性描述器PropertyDescriptor descriptor = new PropertyDescriptor(field.getName(), clazz);//获取field字段的get方法Method readMethod = descriptor.getReadMethod();//执行get方法并填充到表格中row.getCell(i).setText(String.valueOf(readMethod.invoke(item)));//计数器+1i++;}//执行完一行计数器归零i = 0;}mergeCellsVertically(table,0,1,4);}/**** @param table 自己猜* @param col  第几列* @param fromRow  开始行* @param toRow   结束行*/// word跨行并单元格public static void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {XWPFTableCell cell = table.getRow(rowIndex).getCell(col);if ( rowIndex == fromRow ) {// The first merged cell is set with RESTART merge valuecell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);} else {// Cells which join (merge) the first one, are set with CONTINUEcell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);}}}/*** 列的我这里没用,留着备用* @param table* @param row* @param fromCell* @param toCell*/
//    // word跨列合并单元格
//    public  void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
//        for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
//            XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
//            if (cellIndex == fromCell) {
//                // The first merged cell is set with RESTART merge value
//                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
//            } else {
//                // Cells which join (merge) the first one, are set with CONTINUE
//                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
//            }
//        }
//    }}

、、

<!-- 之前打算用这个包的方法开发来着,没研究明白所以放弃了 -->
<dependencies>
<!--        <dependency>-->
<!--            <groupId>e-iceblue</groupId>-->
<!--            <artifactId>spire.doc.free</artifactId>-->
<!--            <version>3.9.0</version>-->
<!--        </dependency>-->
<!--        <dependency>-->
<!--            <groupId>e-iceblue</groupId>-->
<!--            <artifactId>spire.xls.free</artifactId>-->
<!--            <version>3.9.1</version>-->
<!--        </dependency>-->
<!--        <dependency>-->
<!--            <groupId> e-iceblue </groupId>-->
<!--            <artifactId>spire.office</artifactId>-->
<!--            <version>4.8.0</version>-->
<!--        </dependency>-->
</dependencies>
<repositories><repository><id>com.e-iceblue</id><url>https://repo.e-iceblue.cn/repository/maven-public/</url></repository></repositories>

java操作word替换文字和在固定位置插入表格相关推荐

  1. Java读取word模板并在模板相关位置插入数据和表格

    这两天一直在实现这样一个功能,即从数据库及其他数据源中获取相关数据,填充到一定的word模板中,然后将该模板下载下来(主要就是为了以简单的方式让老师看到他想看的系统中不同功能不同位置地方的数据) 最终 ...

  2. java操作word文档(文字,图片,表格添加以及替换操作)

    注:本文由于个人工作需要,有对多个他人博文进行借鉴,但是多数博文都只是讲到了小部分,例如图片/表格的操作,都只有根据书签进行替换,比较片面,本人有总结到根据文字进行图片/表格的替换,希望可以帮到更多有 ...

  3. java操作word,添加页眉,页眉图片,替换书签,添加水印(全)

    java操作word文档,添加页眉文本,页眉图片,替换书签,水印 原模板截图: 生成后的文档效果截图: 第一步:引入maven <dependency><groupId>spi ...

  4. Java操作word模板文件

    关于导出word文档,之前想过用ireport但模板文件比较复杂不容易画.所以采取了Java操作word文件,替换word中的元素方法 模板文件如下 单位名称:$ACCTNAME$ NO: $SN$ ...

  5. Java操作word文档将docx转换为pdf格式

    Java操作word文档将docx转换为pdf格式 一.整体说明 在上传 Office 课件时,格式有:doc,docx,xls,xlsx,ppt,pptx,程序需要将其 转换成 pdf 格式, 才能 ...

  6. java 操作 word 表格和样式,java读取word表格中的表格 java如何读取word中的excel表格数据...

    Java 利用poi 可以直接读取word中的表格保持样式生1.读取word 2003及word 2007需要的jar包 读取 2003 版本(.doc)的word文件相对来说比较简单,只需要 poi ...

  7. Java操作word文件的工具选择

    Java操作word文件的工具选择 使用Java语言,创建doc.docx.excel.pdf等文档,并对文档进行一系列操作. Spire.Doc for Java https://blog.csdn ...

  8. poi操作word替换模板向指定位置添加图表

    poi操作word替换模板向指定位置添加图表 首先是引入pom文件 <dependency><groupId>org.apache.poi</groupId>< ...

  9. java操作word

    前言 使用java操作word使用的是java开源项目docx4j,在学习docx的使用过程中,参考了大牛的链接,下面放上我参考过的网址: http://blog.csdn.net/zhyh1986/ ...

  10. excel在文本的固定位置插入字符、进行日期和时间的合并

    1.excel在文本的固定位置插入字符 如上图,现在想要将其转化为日期格式(比如2017/1/1),但是当设置单元格格式为日期时却显示出很多#.我们可以通过在20170101中添加两个斜杠" ...

最新文章

  1. 关于android.view.WindowLeaked(窗体泄露)的解决方案
  2. 【数据结构与算法】之深入解析Base64编码的实现原理
  3. pandas 季度_pandas_时间序列和常用操作
  4. ArrayList各方法的时间复杂度
  5. python中列表和元组的相同点和不同点_详解Python语言中元组和列表的区别
  6. 【渝粤题库】陕西师范大学100071教育学作业(高起本)
  7. Redis集群之哨兵模式
  8. java 反射静态内部类_android-反射的使用(反射静态内部类、非静态内部类、匿名内部类等)...
  9. php 启动管理工具下载,PHP管理工具compser windows下安装
  10. 程序员:你为什么要离职?
  11. Echart饼图简单使用
  12. Mac无法正常使用共享屏幕功能的解决办法
  13. 概率dp(A - Scout YYF I POJ - 3744 )
  14. 常见的几个接口管理平台简介
  15. 前端页面加载缓慢的原因和性能优化问题
  16. 博客园增加Live2D看板娘教程,超级简单,一看就懂
  17. wps表格宏被禁用如何解禁_wps的excel中宏被禁用怎么办 - 卡饭网
  18. Ubuntu / Python / Mega自动同步监控照片
  19. AES密钥编排Python实现
  20. Silk Zip文件分割器

热门文章

  1. 图标在XMind中应用
  2. 聚美上市后将往何方:服装特卖和100%透明的化妆品渠道
  3. iOS 解决:调用系统相册、相机是英文状态。
  4. 2022年上半年中国企业员工主动离职率大幅下降至6%;三成以上中国企业大部分高管岗位没有后备人选 | 美通社头条...
  5. SQLite数据库中的.db-shm文件和.db-wal文件
  6. win10计算机系统优化设置,这些简单优化能让你的Win10流畅很多
  7. python预处理c语言_C语言预处理器
  8. Excel中用REPT函数制作图表
  9. UnicodeTOGB,能够将Unicode串转换成GB码
  10. Bomb Game(翻译)