import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import lombok.extern.java.Log;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.util.StopWatch;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
@Log
public class FileUtils {
/**
* @param filePath1 文件1,此为合并word时,放在前面的文件
* @param filePath2 文件2,此为合并word时,放在后面的文件
* @param filePath3 文件3,此为合并后保存的文件,可以与文件1、文件2地址相同,此时会覆原先的文件
* @return 返回一个map,state为状态码,200表示执行成功,其他情况表示失败,并返回msg
*/
public static void words(String filePath1, String filePath2, String filePath3) {
Map<String, Object> map = new HashMap<>(16);
map.put("state", "200");
//代码执行结果,默认为200执行正常
try {
//因为调用的jar包把所有异常全部捕获了,所以需要提前判断两个文件是否存在
File file1 = new File(filePath1);
File file2 = new File(filePath2);
if (file1.exists() && file2.exists()) {
StopWatch stopWatch = new StopWatch();
stopWatch.start("合并文档所需时间");
//加载第一个文档
Document doc1 = new Document(filePath1);
//使用insertTextFromFile方法将第二个文档的内容插入到第一个文档
doc1.insertTextFromFile(filePath2, FileFormat.Docx_2013);
//保存文档
doc1.saveToFile(filePath3, FileFormat.Docx_2013);
//去除水印开始
InputStream is = new FileInputStream(filePath3);
XWPFDocument document = new XWPFDocument(is);
//以上Spire.Doc 生成的文件会自带警告信息,这里来删除Spire.Doc 的警告
//此行若影响标题可注释
document.removeBodyElement(0);
//输出word内容文件流,新输出路径位置
OutputStream os=new FileOutputStream(filePath3);
try {
document.write(os);
System.out.println("生成无水印文档成功!");
} catch (Exception e) {
e.printStackTrace();
}
stopWatch.stop();
log.info(stopWatch.prettyPrint());
} else if (!file1.exists() && file2.exists()) {
map.put("state", "-1");
map.put("msg", "文件合并失败,目标文件不存在:" + filePath1);
log.info("文件合并失败,目标文件不存在:" + filePath1);
// return map;
} else if (file1.exists() && !file2.exists()) {
map.put("state", "-1");
map.put("msg", "文件合并失败,目标文件不存在:" + filePath2);
log.info("文件合并失败,目标文件不存在:" + filePath2);
// return map;
} else if (!file1.exists() && !file2.exists()) {
map.put("state", "-1");
map.put("msg", "文件合并失败,目标文件不存在:" + filePath1 + ",目标文件不存在:" + filePath2);
log.info("文件合并失败,目标文件不存在:" + filePath1 + ",目标文件不存在:" + filePath2);
// return map;
}
} catch (Exception e) {
map.put("state", "-1");
map.put("msg", "文件合并失败,相关文件1:" + filePath1 + ",相关文件2:" + filePath2);
log.info("文件合并失败,相关文件1:" + filePath1 + ",相关文件2:" + filePath2);
e.printStackTrace();
}
// return map;
}
}
11-11
1820