许鹏程
2024-09-30 f1579ea6e661af4ed4fb4d4a1dbbe4f5bc75c284
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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;
        }
    }
}