批量导出word,并导出一个zip文件
创始人
2025-01-15 23:04:33
0

系统导出功能,多条数据分别导出word,多个word打包到一个zip进行导出,直接拷贝过去可用,如果缺包自行查找。

参考: Java使用word模板导出word_java根据模板导出word-CSDN博客.

    @Action(value = "exportToWordZip")     public String exportToWordZip() throws Exception {         HttpServletRequest request = ServletActionContext.getRequest();         WordUtil xwpfTUtil = null;         FileOutputStream os = null;         InputStream is = null;         List files = new ArrayList<>();         for (int i = 0; i < 2; i++) {             //导出的数据处理             Map params = new HashMap<>();             params.put("${Name}", "Fisher3652");             params.put("${Sex}", "男");             params.put("${Desc}", "18岁\tJAVA开发\r熟悉JVM基本原理");             params.put("${@Pic}", "C:\\Users\\admin\\Desktop\\资源\\32.png");              //获取模版             is = FileUtil.class.getClassLoader().getResourceAsStream("static/letterWordDemo.docx");             xwpfTUtil = new WordUtil();             CustomXWPFDocument doc;             doc = new CustomXWPFDocument(is);             //模版替换成真实数据             xwpfTUtil.replaceInPara(doc, params);             xwpfTUtil.replaceInTable(doc, params);             //生成word到临时文件             String realPath = request.getSession().getServletContext().getRealPath("/");             String parentPath = new File(realPath).getParent() + "/exportToWordZipTemp" ;             File dir = new File(parentPath);             if (!dir.exists()) {                 dir.mkdirs();             }             String fileName = parentPath + "/" + i + ".docx";             System.out.println(fileName);             os = new FileOutputStream(fileName);             files.add(fileName);             doc.write(os);             System.out.println("word成功生成");         }         xwpfTUtil.close(os);         xwpfTUtil.close(is);         os.flush();         os.close();         writeZip(files, "文件汇总");         return null;     } 
package com.dazhi.itp.util.exportWord;  import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlToken; import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;  import java.io.IOException; import java.io.InputStream;  public class CustomXWPFDocument extends XWPFDocument {     public CustomXWPFDocument(InputStream in) throws IOException {         super(in);     }      public CustomXWPFDocument(OPCPackage pkg) throws IOException {         super(pkg);     }      public void createPicture(String blipId,int id, int width, int height, XWPFParagraph paragraph)     {         final int EMU = 9525;         width *= EMU;         height *= EMU;          //给段落插入图片         CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();          String picXml = "" +                 "" +                 "   " +                 "      " +                 "         " +                 "            " +                 "            " +                 "         " +                 "         " +                 "            " +                 "            " +                 "               " +                 "            " +                 "         " +                 "         " +                 "            " +                 "               " +                 "               " +                 "            " +                 "            " +                 "               " +                 "            " +                 "         " +                 "      " +                 "   " +                 "";          XmlToken xmlToken = null;         try         {             xmlToken = XmlToken.Factory.parse(picXml);         }         catch(XmlException xe)         {             xe.printStackTrace();         }         inline.set(xmlToken);          inline.setDistT(0);         inline.setDistB(0);         inline.setDistL(0);         inline.setDistR(0);          CTPositiveSize2D extent = inline.addNewExtent();         extent.setCx(width);         extent.setCy(height);          CTNonVisualDrawingProps docPr = inline.addNewDocPr();         docPr.setId(id);         docPr.setName("Picture " + id);         docPr.setDescr("Generated");     } }   
package com.dazhi.itp.util.exportWord;  import com.dazhi.itp.util.exportWord.CustomXWPFDocument; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.xwpf.usermodel.*;  import java.io.*; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;  public class WordUtil {      /**      * 替换段落里面的变量      *      * @param doc    要替换的文档      * @param params 参数      * @throws FileNotFoundException      * @throws InvalidFormatException      */     public void replaceInPara(CustomXWPFDocument doc, Map params) throws InvalidFormatException, FileNotFoundException {         Iterator iterator = doc.getParagraphsIterator();         XWPFParagraph para;         while (iterator.hasNext()) {             para = iterator.next();             this.replaceInPara(para, params,doc);         }     }      /**      * 替换段落里面的变量      * 文本用${}标识,例如${Name},图片用${@},多一个@标识      * @param para   要替换的段落      * @param params 参数      * @throws FileNotFoundException      * @throws InvalidFormatException      */     public void replaceInPara(XWPFParagraph para, Map params, CustomXWPFDocument doc) throws InvalidFormatException, FileNotFoundException {         List runs;         Matcher matcher;         if (this.matcher(para.getParagraphText()).find()) {             runs = para.getRuns();             int start = -1;             int end = -1;             String str = "";             String text= "";             for (int i = 0; i < runs.size(); i++) {                 text += runs.get(i).toString();             }             for (int i = 0; i < runs.size(); i++) {                 XWPFRun run = runs.get(i); //                System.out.println("------>>>>>>>>>" + text);                 if (text.contains("$")) {                     start = text.indexOf("$");                 }                 if ((start != -1)) {                     str += text.substring(text.indexOf("$"), text.length()).trim();                     String paraList=runs.toString(); //                    System.out.println("未删除前"+paraList);                     Object[] runArr = runs.toArray();                     int size=runs.size();                     int $Index=0;                     for (int j = 0; j < runArr.length; j++) {                         if (runArr[j].toString().contains("$")) {                             $Index=j;                             break;                         }                     }                     int startIn=$Index;                     while (startIn"+start); //            System.out.println("end--->"+end); //            System.out.println("str---->>>" + str);              for (String key : params.keySet()) {                 if (str.equals(key)) {                     //判断是图片还是文本                     if(str.indexOf("@")==-1){                         String value= params.get(key).toString();                         para.createRun().setText(value);                         break;                     }else{                         //图片处理                         String value= params.get(key).toString();                         int length = para.getRuns().size();                         if (length > 0) {                             for (int i = (length - 1); i >= 0; i--) {                                 para.removeRun(i);                             }                         }                         String blipId = doc.addPictureData(new FileInputStream(new File(value)), CustomXWPFDocument.PICTURE_TYPE_PNG);                         doc.createPicture(blipId,doc.getNextPicNameNumber(CustomXWPFDocument.PICTURE_TYPE_PNG), 550, 250,para);                         break;                     }                 }             }           }     }      /**      * 替换表格里面的变量      *      * @param doc    要替换的文档      * @param params 参数      * @throws FileNotFoundException      * @throws InvalidFormatException      */     public void replaceInTable(CustomXWPFDocument doc, Map params) throws InvalidFormatException, FileNotFoundException {         Iterator iterator = doc.getTablesIterator();         XWPFTable table;         List rows;         List cells;         List paras;         while (iterator.hasNext()) {             table = iterator.next();             rows = table.getRows();             for (XWPFTableRow row : rows) {                 cells = row.getTableCells();                 for (XWPFTableCell cell : cells) {                     paras = cell.getParagraphs();                     for (XWPFParagraph para : paras) {                         this.replaceInPara(para, params,doc);                     }                 }             }         }     }      /**      * 正则匹配字符串      *      * @param str      * @return      */     private Matcher matcher(String str) {         Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);         Matcher matcher = pattern.matcher(str);         return matcher;     }      /**      * 关闭输入流      *      * @param is      */     public void close(InputStream is) {         if (is != null) {             try {                 is.close();             } catch (IOException e) {                 e.printStackTrace();             }         }     }      /**      * 关闭输出流      *      * @param os      */     public void close(OutputStream os) {         if (os != null) {             try {                 os.close();             } catch (IOException e) {                 e.printStackTrace();             }         }     } }   

模版

相关内容

热门资讯

二次测试微扑克算正规平台的(软... 【福星临门,好运相随】;二次测试微扑克算正规平台的(软件)wpk微扑克真的有助辅的(2020已更新)...
玩家必备辅助(咪咪扑克)软件透... 玩家必备辅助(咪咪扑克)软件透明挂(辅助挂)透明辅助挂软件(2023已更新)(哔哩哔哩);超受欢迎的...
6次存在wepoke外挂(插件... 6次存在wepoke外挂(插件)微扑克有辅助软件的(2024已更新)(哔哩哔哩);AI辅助机器人普及...
6分钟测试wpk辅助透视(软件... 6分钟测试wpk辅助透视(软件)wepoke软件透明下载渠道(2022已更新)(哔哩哔哩)是一款可以...
一分钟带你了解(德州微扑克)软... 一分钟带你了解(德州微扑克)软件透明挂(辅助挂)透明挂测试(2022已更新)(哔哩哔哩);是一款可以...
七分钟系统线上wpk到底有外挂... 七分钟系统线上wpk到底有外挂(脚本)wpk代打是真的的(2021已更新)(哔哩哔哩);致您一封信;...
Ubuntu上安装、使用Red... 这篇文章简单地介绍一下怎么在linux虚拟机上完成redis的安装及使用。目录1、安装redis2、...
专业讨论(德州线上扑克)软件透... 您好,德州线上扑克这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款...
2021版AI微扑克有后台控制... 2021版AI微扑克有后台控制的(开挂)wpk机制(2021已更新)(哔哩哔哩);一、微扑克有挂的是...
Springboot项目-基于... 大家好!我是程序猿老A,感谢您阅读本文,欢迎一键三连哦。&...