java word 模板替换

package com.cyb.pm.util.wordTemplate;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFPicture;
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 com.cyb.utils.IdCardGenerator;
import com.cyb.utils.date.DateUtil;
import com.cyb.utils.random.RandomUtils;

public class WordTemplateWriter {
	 static XWPFDocument document = null;
	 
	 public static Map getDataMap() {
		 Map dataMap = new HashMap<>();
         dataMap.put("name", "张三");
         dataMap.put("age", "25");
         dataMap.put("gender", "男");
          int num = new Random().nextInt(5)+1;
          System.out.println("列表随机行数:"+num);
          if(num>6) num=6;
          for(int i=1;i<=num;i++) {//实际记录数补充真实值。
             dataMap.put("a"+i,RandomUtils.getChineaseName());
             dataMap.put("b"+i, RandomUtils.getPassWord(10));
             dataMap.put("c"+i, IdCardGenerator.generate());
             Date d=DateUtil.preDate(new Random().nextInt(500));
             dataMap.put("d"+i, DateUtil.date2long8(d).toString());
             dataMap.put("e"+i, RandomUtils.getRoad());
          }
          //固定表格长度5,剩余填空
          for(int j=num+1;j<=6;j++) {
         	 dataMap.put("a"+j, "");
              dataMap.put("b"+j, "");
              dataMap.put("c"+j,"");
              dataMap.put("d"+j,"");
              dataMap.put("e"+j,"");
          }
          System.out.println(dataMap);
          return dataMap;
	 }
    public static void main(String[] args) throws Exception {
        try {
            // 打开模板文件
            FileInputStream templateFile = new FileInputStream("d://data//muban//template.docx");
            document = new XWPFDocument(templateFile);

            // 定义需要替换的数据
            Map dataMap = getDataMap();
            // 替换模板中的占位符
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                replacePlaceholder(paragraph, dataMap);
            }
            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph paragraph : cell.getParagraphs()) {
                            replacePlaceholder(paragraph, dataMap);
                        }
                    }
                }
            }
            
            
            
            
            // 读取新图片文件
            FileInputStream newImageFile = new FileInputStream("d://data//muban/1.png");
            byte[] newImageData = IOUtils.toByteArray(newImageFile);
            newImageFile.close();
//            // 获取模板中的所有图片
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                for (XWPFRun run : paragraph.getRuns()) {
                    for (XWPFPicture picture : run.getEmbeddedPictures()) {
                        // 替换图片数据
                        //String oldImageName = picture.getCTPicture().getBlipFill().getBlip().getEmbed();
                       // byte[] oldImageData = document.getPackagePart().getPartByName(oldImageName).getInputStream()
                                //.readAllBytes();
                       // document.getPackagePart().removePart(document.getPackagePart().getRelationships().getRelationshipByID(oldImageName));
                        String newImageName = document.addPictureData(newImageData, Document.PICTURE_TYPE_PNG);
                        picture.getCTPicture().getBlipFill().getBlip().setEmbed(newImageName);
                        // 设置新图片大小
                        picture.getCTPicture().getSpPr().getXfrm().getExt().setCx(400);
                        picture.getCTPicture().getSpPr().getXfrm().getExt().setCy(300);
                    }
                }
            }
            
//            // 准备循环列表数据
//            List dataList = new ArrayList<>();
//            dataList.add("数据项1");
//            dataList.add("数据项2");
//            dataList.add("数据项3");
//            // 查找模板中的占位符
//            for (XWPFParagraph paragraph : document.getParagraphs()) {
//                String text = paragraph.getText();
//                if (text.contains("${studentList}")) {
//                    // 删除包含占位符的段落
//                    document.removeBodyElement(document.getPosOfParagraph(paragraph));
//                    // 在模板段落之前插入循环部分
//                    for (String data : dataList) {
//                        XWPFParagraph newDataParagraph = document.insertNewParagraph(paragraph.getCTP().newCursor());
//                        XWPFRun run = newDataParagraph.createRun();
//                        run.setText(data);
//                    }
//                    //insertTableList(document);
//                    break;
//                }
//            }
            newImageFile = new FileInputStream("d://data//muban/1.png");
            newImageData = IOUtils.toByteArray(newImageFile);
            newImageFile.close();
            // 遍历文档中的所有段落
            for (XWPFParagraph para : document.getParagraphs()) {
                List runs = para.getRuns();
                for (int i = 0; i < runs.size(); i++) {
                    XWPFRun run = runs.get(i);
                    String text = run.getText(0);
                    if (text != null && text.contains("Image1")) {
                        // 清除原有文本
                        run.setText("", 0);
                         //插入图片
                        String imagePath = "d://data//muban/1.png";
                        FileInputStream imageStream = new FileInputStream(imagePath);
                        String imageId = document.addPictureData(newImageData, Document.PICTURE_TYPE_PNG);
                        System.out.println(imageId);
                        int width = 200; // 设置图片宽度(单位:像素)
                        int height = 200; // 设置图片高度(单位:像素)
                        run.addPicture(imageStream, XWPFDocument.PICTURE_TYPE_PNG, "1.png", width, height);
                    }
                }
            }

            // 保存文件
            FileOutputStream outputFile = new FileOutputStream("d://data//muban/output.docx");
            document.write(outputFile);
            outputFile.close();

            System.out.println("数据写入 Word 模板成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void insertTableList(XWPFDocument document) {
    	 List personList = new ArrayList<>();
         personList.add(new Person("张三", 25));
         personList.add(new Person("李四", 30));
         personList.add(new Person("王五", 28));

         // 创建一个表格
         XWPFTable table = document.createTable();
         table.setWidth("100%");
         // 创建表头行
         XWPFTableRow headerRow = table.getRow(0);
         headerRow.getCell(0).setText("姓名");
         headerRow.addNewTableCell().setText("年龄");
         // 在表格中输出循环数据
         for (Person person : personList) {
         	System.out.println(person.getAge());
             XWPFTableRow row = table.createRow();
             row.getCell(0).setText(person.getName());
             row.getCell(1).setText(Integer.toString(person.getAge()));
         }
    }
    
    private static void replacePlaceholder(XWPFParagraph paragraph, Map dataMap) throws Exception {
        for (XWPFRun run : paragraph.getRuns()) {
            String text = run.getText(0);
            if (text != null) {
//            	if( text.contains("Image1")) {
//            		 document.removeBodyElement(document.getPosOfParagraph(paragraph));
//            		// 插入图片
//                    String imagePath = "d://data//muban/1.png";
//                    FileInputStream imageStream = new FileInputStream(imagePath);
//                    String imageId = document.addPictureData(imageStream, Document.PICTURE_TYPE_PNG);
//                    int width = 200; // 设置图片宽度(单位:像素)
//                    int height = 200; // 设置图片高度(单位:像素)
//                    run.addPicture(imageStream, XWPFDocument.PICTURE_TYPE_PNG, imageId, width, height);
//            	}else 
            	{
	                for (Map.Entry entry : dataMap.entrySet()) {
	                    String placeholder = "${" + entry.getKey() + "}";
	                    if (text.contains(placeholder)) {
	                        text = text.replace(placeholder, entry.getValue());
	                        run.setText(text, 0);
	                    }
	                }
            	}
            }
        }
    }
}
class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

你可能感兴趣的:(java,word)