package com.product.file.util; import cn.hutool.core.lang.UUID; import com.product.core.config.Global; import com.spire.doc.*; import java.io.*; public class MergeWordDocuments { public static File mergeFile(File source, File target) throws Exception { if ("doc".equals(FileUtil.checkDocType(source))) { source = FileUtil.toDocx(source); } boolean delTarget = false; if ("doc".equals(FileUtil.checkDocType(target))) { target = FileUtil.toDocx(target); delTarget = true; } try (InputStream sourceIn = new FileInputStream(source); InputStream targetIn = new FileInputStream(target)) { Document sourceDoc = new Document(sourceIn); Document targetDoc = new Document(targetIn); for (Object section : targetDoc.getSections()) { Section sec = (Section) section; for (Object docObj : sec.getBody().getChildObjects()) { DocumentObject obj = (DocumentObject) docObj; Section lastSection = sourceDoc.getLastSection(); Body body = lastSection.getBody(); body.getChildObjects().add(obj.deepClone()); } } String fileType=".docx"; FileFormat saveType = FileFormat.Docx; //判断来源文件是否为wps if (source.getName().endsWith(".wps")) { saveType = FileFormat.WPS; fileType=".wps"; } // doc.insertTextFromStream(targetIn, com.spire.doc.FileFormat.Docx); String tempFile = Global.getSystemConfig("temp.dir", "./attachment/temp") + File.separator + UUID.randomUUID() + fileType; try (FileOutputStream out = new FileOutputStream(tempFile)) { sourceDoc.saveToStream(out, FileFormat.Docx); return new File(tempFile); } catch (IOException e) { throw e; } finally { if (delTarget) { target.delete(); } // doc.close(); } } catch (IOException e) { throw e; } catch (Exception e) { throw e; } } }