欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

POI操作word填充数据

程序员文章站 2022-04-11 18:15:14
...

1、pom引入POI包

 

            <!--poid-->
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>3.17}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>3.17</version>
            </dependency>
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml-schemas</artifactId>
                <version>3.17</version>
            </dependency>

2、POI的XWPFDocument往word模板中填充数据

package com.sx.local.govern.utils;

import com.sx.common.util.FileUtil;
import com.sx.common.util.SpringContextHolder;
import com.sx.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.core.env.Environment;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @deprecated word工具类
 * @author lst
 * @since 2020-10-26
 */
@Slf4j
public class WordUtils {

    private static Environment environment = SpringContextHolder.getBean(Environment.class);

    /**
     * 根据指定的参数值、模板,生成 word 文档
     * @param param    需要替换的变量
     * @param templatePath 模板
     */
    public static void generateWord(Map<String, Object> param, String templatePath, HttpServletResponse response) {
        CustomXWPFDocument doc = null;
        try {
            OPCPackage pack = POIXMLDocument.openPackage(templatePath);
            doc = new CustomXWPFDocument(pack);
            // 处理段落
            List<XWPFParagraph> paragraphList = doc.getParagraphs();
            processParagraphs(paragraphList, param, doc);

            // 处理表格
            Iterator<XWPFTable> it = doc.getTablesIterator();
            while (it.hasNext()) {
                XWPFTable table = it.next();
                List<XWPFTableRow> rows = table.getRows();
                for (XWPFTableRow row : rows) {
                    List<XWPFTableCell> cells = row.getTableCells();
                    for (XWPFTableCell cell : cells) {
                        List<XWPFParagraph> paragraphListTable = cell.getParagraphs();
                        processParagraphs(paragraphListTable, param, doc);
                    }
                }
            }
            // 输出文件
            OutputStream outputStream = response.getOutputStream();
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + new String((DateUtil.getDateTime14() + ".docx").getBytes(), "ISO8859-1"));
            response.setContentType("application/octet-stream");
            doc.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            log.error("错误信息:{}",e.getMessage());
        }
    }


    /**
     * word单元格水平垂直居中
     * @param cell
     * @return
     */
    public static XWPFTableCell horizontalVerticalCenter(XWPFTableCell cell) {
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);//垂直居中
        CTTc cttc = cell.getCTTc();
        CTP ctp = cttc.getPList().get(0);
        CTPPr ctppr = ctp.getPPr();
        if (ctppr == null) {
            ctppr = ctp.addNewPPr();
        }
        CTJc ctjc = ctppr.getJc();
        if (ctjc == null) {
            ctjc = ctppr.addNewJc();
        }
        ctjc.setVal(STJc.CENTER); //水平居中
        return cell;
    }

    /**
     * 处理段落
     *
     * @param paragraphList
     * @throws FileNotFoundException
     * @throws InvalidFormatException
     */
    public static void processParagraphs(List<XWPFParagraph> paragraphList, Map<String, Object> param, XWPFDocument doc)
            throws InvalidFormatException, FileNotFoundException {
          if (paragraphList != null && paragraphList.size() > 0) {
              for (XWPFParagraph paragraph : paragraphList) {
                  List<XWPFRun> runs = paragraph.getRuns();
                  String text = "", color = "";
                  for (XWPFRun run : runs) {
                      try {
                          String t = run.getText(0);
                          if (t != null) {
                              color = run.getColor();
                              text += t;
                          }
                      } catch (Exception e) {
                          log.info(e.toString());
                      }

                  }
                  if (StringUtil.isNotEmpty(text)) {
                      boolean isSetText = false;
                      Boolean flag = true;
                      for (Map.Entry<String, Object> entry : param.entrySet()) {
                          String key = entry.getKey();
                          key = "$" + key ;
                          if (text.indexOf(key) != -1) {
                              isSetText = true;
                              flag = false;
                              Object value = entry.getValue();
                              //text = text.replace(key, value.toString());
                              if (StringUtil.isNotEmpty(value)) {
                                  //替换
                                  if (value instanceof String && (!(value.toString().indexOf("http://") > -1) || !(value.toString().substring(value.toString().lastIndexOf(".")).indexOf(".") > -1))) {
                                      text = text.replace(key, value.toString());
                                  } else {
                                      if (text.indexOf(key) != -1) {
                                          String imgurl = value.toString();
                                          //String type = value.toString().substring(value.toString().length()-3);
                                          String type = value.toString().substring(value.toString().lastIndexOf(".")).replace(".", "");
                                          log.info("文件类型:{}" , type);
                                          if (getPictureType(type) != 4) {
                                              //特殊处理图片
                                              int length = paragraph.getRuns().size();
                                              //将原有的Run去掉
                                              if (length > 0) {
                                                  for (int i = (length - 1); i >= 0; i--) {
                                                      paragraph.removeRun(i);
                                                  }
                                              }
                                              log.info("key:{}" , key);
                                              log.info("imgurl:{}" , imgurl);
                                              String fileNamePath = environment.getProperty("file.uploadPath");
                                              log.info("文件路径:{}" , fileNamePath);
                                              //File file = new File("D://" + imgurl.substring(imgurl.lastIndexOf("/")));
                                              File file = new File(fileNamePath);
                                              String fileStrPath = fileNamePath.substring(0, fileNamePath.lastIndexOf("/") + 1);
                                              log.info("文件夹路径1:{}" ,fileStrPath);
                                              File fileDir = new File(fileStrPath);
                                              if (!fileDir.exists()) {
                                                  log.info("创建文件夹");
                                                  fileDir.mkdirs();
                                              }
                                              if (!file.exists()) {
                                                  log.info("文件不存在,正在完成下载。。。");
                                                  //FileUtils.downloadFromNet(imgurl,"D://" + imgurl.substring(imgurl.lastIndexOf("/")));
                                                  FileUtil.downloadFromNetByCode(imgurl, fileNamePath);
                                              }


                                              int width = 280;//默认
                                              int height = 200;//默认
                                              CustomXWPFDocument cusDoc = (CustomXWPFDocument) doc;
                                              //String blipId = cusDoc.addPictureData(new FileInputStream(new File("D://" + imgurl.substring(imgurl.lastIndexOf("/")))), getPictureType(type));
                                              String blipId = cusDoc.addPictureData(new FileInputStream(new File(fileNamePath)), getPictureType(type));
                                              cusDoc.createPicture(blipId, doc.getNextPicNameNumber(getPictureType(type)), width, height, paragraph);
                                          }
                                      }
                                  }
                              } else {
                                  //若value为空,组装""
                                  text = text.replace(key, "");
                              }
                          }
                      }
                      //说明map中没有模板的key  默认为空
                      if(flag && text.startsWith("$")){
                          isSetText = true;
                          //若value为空,组装""
                          text = text.replace(text, "");
                      }
                      if (isSetText) {
                          runs.get(0).setText(text, 0);
                          if (StringUtil.isNotEmpty(color)) {
                              runs.get(0).setColor(color);
                          }
                          for (int i = 1; i < runs.size(); i++) {
                              runs.get(i).setText("", 0);
                          }
                      }
                  }
              }
          }
    }

    /**
     * 根据图片类型,取得对应的图片类型代码
     *
     * @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) throws Exception {
       //调用
       Map<String,Object> mapRtn = new HashMap();
       mapRtn.put("name","张三");
       String temPath = "F:\file\fileUpload\\enclosureOne.docx";
       generateWord(mapRtn,temPath,response);
    }

    /**
     * word 转pdf
     * @param docxFilePath
     * @param pdfFilePath
     * @return
     */
    public static String convertPdf(String docxFilePath, String pdfFilePath) {

        try {
            File docxFile = new File(docxFilePath);
            //File pdfFile = new File(pdfFilePath);
            // 转换pdf文件
            if (docxFile.exists()) {
                InputStream inStream = new FileInputStream(docxFilePath);
                XWPFDocument document = new XWPFDocument(inStream);
                // HWPFDocument document = new HWPFDocument(inStream);
                OutputStream out = new FileOutputStream(pdfFilePath);
                PdfOptions options = PdfOptions.create();
                // ExtITextFontRegistry fontProvider=ExtITextFontRegistry.getRegistry();
                // options.fontProvider(fontProvider);
                PdfConverter.getInstance().convert(document, out, options);
                out.close();
                inStream.close();
            } else {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pdfFilePath;
    }

}

3、模板

POI操作word填充数据

 

4、测试

POI操作word填充数据

 

 

相关标签: java poi