| | |
| | | package com.product.file.service; |
| | | |
| | | import cn.hutool.core.io.FileUtil; |
| | | import com.product.file.util.AsposeUtil; |
| | | import com.product.file.util.FileUtils; |
| | | import org.apache.poi.openxml4j.opc.OPCPackage; |
| | | import org.apache.poi.xwpf.usermodel.XWPFDocument; |
| | | import org.apache.tomcat.util.http.fileupload.IOUtils; |
| | |
| | | * @param response 合并后的docx输出文件 |
| | | */ |
| | | public static File mergeDoc(List<File> srcDocxs, String tempFilePath) { |
| | | OutputStream dest = null; |
| | | List<OPCPackage> opcpList = new ArrayList<>(); |
| | | int length = null == srcDocxs ? 0 : srcDocxs.size(); |
| | | /** |
| | | * 循环获取每个docx文件的OPCPackage对象 |
| | | */ |
| | | for (int i = 0; i < length; i++) { |
| | | File doc = srcDocxs.get(i); |
| | | OPCPackage srcPackage = null; |
| | | try { |
| | | srcPackage = OPCPackage.open(doc); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | if (srcDocxs.size() > 1) { |
| | | File file = srcDocxs.get(0); |
| | | for (int i = 1; i < srcDocxs.size(); i++) { |
| | | file = AsposeUtil.mergeWord(file, srcDocxs.get(i)); |
| | | } |
| | | if (null != srcPackage) { |
| | | opcpList.add(srcPackage); |
| | | } |
| | | } |
| | | int opcpSize = opcpList.size(); |
| | | //获取的OPCPackage对象大于0时,执行合并操作 |
| | | if (opcpSize > 0) { |
| | | try { |
| | | dest = new FileOutputStream(tempFilePath); |
| | | XWPFDocument src1Document = new XWPFDocument(opcpList.get(0)); |
| | | CTBody src1Body = src1Document.getDocument().getBody(); |
| | | //OPCPackage大于1的部分执行合并操作 |
| | | if (opcpSize > 1) { |
| | | for (int i = 1; i < opcpSize; i++) { |
| | | OPCPackage src2Package = opcpList.get(i); |
| | | XWPFDocument src2Document = new XWPFDocument(src2Package); |
| | | CTBody src2Body = src2Document.getDocument().getBody(); |
| | | appendBody(src1Body, src2Body); |
| | | } |
| | | } |
| | | //将合并的文档写入目标文件中 |
| | | src1Document.write(dest); |
| | | return new File(tempFilePath); |
| | | } catch (FileNotFoundException e) { |
| | | e.printStackTrace(); |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } finally { |
| | | //关闭流 |
| | | IOUtils.closeQuietly(dest); |
| | | } |
| | | FileUtil.copyFile(file, new File(tempFilePath)); |
| | | FileUtil.del(file); |
| | | } |
| | | return null; |
| | | } |