将多个word文件合并成一个文件导出
public void bigPrintLabel(printLabelReq req, HttpServletRequest request, HttpServletResponse response) throws Exception {
Optional<Sample> optionalSample = sampleRepository.findById(req.getId());
ValidationUtil.isNull(optionalSample, "Sample", "id", req.getId());
Sample sample = optionalSample.get();
LabOrder labOrder = sample.getLabOrder();
List<Map<String, String>> list = new ArrayList<>();
List<XWPFDocument> xwpfDocuments = new ArrayList<XWPFDocument>();
for (Integer i = 1; i <= req.getNumber(); i++) {
Map<String, String> param = new HashMap<>();
if (i < 10) {
param.put("${sampleNum}", labOrder.getOrderNumber() + "-0" + i);
} else {
param.put("${sampleNum}", labOrder.getOrderNumber() + "-" + i);
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd");
//word中需要填入数据的地方使用${*}替换
param.put("${receiveTime}", simpleDateFormat.format(sample.getReceiveTime()));
param.put("${completTime}", simpleDateFormat.format(labOrder.getDeadline()));
param.put("${sampleName}", sample.getSampleName());
param.put("${sampleModle}", sample.getSampleModel());
param.put("${sampleRemark}", sample.getReceiveNum() + labOrder.getUnit());
param.put("${client}", labOrder.getContact().getClient().getCompany());
param.put("${makeUnit}", labOrder.getFactoryName());
param.put("${address}", labOrder.getContact().getClient().getAddress());
list.add(param);
}
for (Map<String, String> map : list) {
//此处需要一个绝对路径,因为上传阿里云服务器,无法确定路径值,使用以下方法获取绝对路径
String path = "tempLabel/";
String fileName = "fulisiyangpinbiaoqian.docx";
File outTempFile = new File(path + fileName);
XWPFDocument xwpfDocument = generateWord(map, outTempFile.getAbsolutePath());
xwpfDocuments.add(xwpfDocument);
}
//这样第一步将所有word内容替换之后生成多个 xwpfDocument
//现在将多个xwpfDocument 进行合并 追加 生成word文件
//先获取一个模板 以第一个模板为基础进行追加
XWPFDocument xwpfDocument = xwpfDocuments.get(0);
for (int i = 0; i < xwpfDocuments.size(); i++) {
//每次的追加为了避免样式和格式混乱 加上分页符
//当是只有一条数据的时候 直接输出
if (i == 0) {
xwpfDocument = xwpfDocuments.get(0);
//xwpfDocuments.get(1).createParagraph().createRun().addBreak(BreakType.PAGE);
continue;
} else {
//当存在多条时候
xwpfDocument = mergeWord(xwpfDocument, xwpfDocuments.get(i));
}
}
//合并之后返回XWPFDocument对象 写出就可以了
String filePath = "tempFile/";
String fileName = "biaoqian.doc";
File outFile = new File(filePath + fileName);
if (!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdirs();
}
if (!outFile.exists()) {
outFile.createNewFile();
}
OutputStream outputStream = new FileOutputStream(outFile);
xwpfDocument.write(outputStream);
}
public static XWPFDocument generateWord(Map<String, String> param, String filePath) {
XWPFDocument doc = null;
try {
OPCPackage pack = POIXMLDocument.openPackage(filePath);
doc = new XWPFDocument(pack);
if (param != null && param.size() > 0) {
//处理段落
String tempString = "";
Set<XWPFRun> runSet = new HashSet<>();
char lastChar = ' ';
List<XWPFParagraph> paragraphList = doc.getParagraphs();
if (paragraphList != null && paragraphList.size() > 0) {
for (XWPFParagraph paragraph : paragraphList) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String text = run.getText(0);
//文件里含有特殊字符,无法正常显示
if ("1".equals(text)) {
if ("1".equals(param.get("pending"))) {
text = text.replace("1", "☑");
run.setText(text, 0);//往文本里添加一个打勾方框符号
} else {
text = text.replace("1", "□");
run.setText(text, 0);//往文本里添加一个打勾方框符号
}
}
if ("2".equals(text)) {
if ("1".equals(param.get("inspection"))) {
text = text.replace("2", "☑");
run.setText(text, 0);//往文本里添加一个打勾方框符号
} else {
text = text.replace("2", "□");
run.setText(text, 0);//往文本里添加一个打勾方框符号
}
}
if ("3".equals(text)) {
if ("1".equals(param.get("checked"))) {
text = text.replace("3", "☑");
run.setText(text, 0);//往文本里添加一个打勾方框符号
} else {
text = text.replace("3", "□");
run.setText(text, 0);//往文本里添加一个打勾方框符号
}
}
if ("4".equals(text)) {
if ("1".equals(param.get("abnormal"))) {
text = text.replace("4", "☑");
run.setText(text, 0);//往文本里添加一个打勾方框符号
} else {
text = text.replace("4", "□");
run.setText(text, 0);//往文本里添加一个打勾方框符号
}
}
if ("5".equals(text)) {
if ("1".equals(param.get("reserve"))) {
text = text.replace("5", "☑");
run.setText(text, 0);//往文本里添加一个打勾方框符号
} else {
text = text.replace("5", "□");
run.setText(text, 0);//往文本里添加一个打勾方框符号
}
}
if (text == null) continue;
text = replaceText(text, param);
run.setText("", 0);
run.setText(text, 0);
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
//System.out.println(ch);
if (ch == '$') {
runSet = new HashSet<>();
runSet.add(run);
tempString = text;
} else if (ch == '{') {
if (lastChar == '$') {
if (runSet.contains(run)) {
} else {
runSet.add(run);
tempString = tempString + text;
}
} else {
runSet = new HashSet<>();
tempString = "";
}
} else if (ch == '}') {
if (tempString != null && tempString.indexOf("${") >= 0) {
if (runSet.contains(run)) {
} else {
runSet.add(run);
tempString = tempString + text;
}
} else {
runSet = new HashSet<>();
tempString = "";
}
if (runSet.size() > 0) {
System.out.println(tempString);
String replaceText = replaceText(tempString, param);
if (!replaceText.equals(tempString)) {
int index = 0;
XWPFRun aRun = null;
for (XWPFRun tempRun : runSet) {
tempRun.setText("", 0);
if (index == 0) {
aRun = tempRun;
}
index++;
}
aRun.setText(replaceText, 0);
}
runSet = new HashSet<>();
tempString = "";
}
} else {
if (runSet.size() <= 0) continue;
if (runSet.contains(run)) continue;
runSet.add(run);
tempString = tempString + text;
}
lastChar = ch;
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
private static String replaceText(String text, Map<String, String> map) {
if (text != null) {
System.out.println(text);
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
if (text.indexOf(key) != -1) {
Object value = entry.getValue();
if (value instanceof String) {//文本替换
text = text.replace(key, value.toString());
}
}
}
}
return text;
}
//两个对象进行追加
public static XWPFDocument mergeWord(XWPFDocument document, XWPFDocument doucDocument2) throws Exception {
XWPFDocument src1Document = document;
//XWPFParagraph p = src1Document.createParagraph();
//设置分页符
//p.setPageBreak(true);
CTBody src1Body = src1Document.getDocument().getBody();
XWPFDocument src2Document = doucDocument2;
CTBody src2Body = src2Document.getDocument().getBody();
//下面这句会在尾部多一个换行符
//XWPFParagraph p2 = src2Document.createParagraph();
XmlOptions optionsOuter = new XmlOptions();
optionsOuter.setSaveOuter();
String appendString = src2Body.xmlText();
String srcString = src1Body.xmlText();
String prefix = srcString.substring(0, srcString.indexOf(">") + 1);
String mainPart = srcString.substring(srcString.indexOf(">") + 1, srcString.lastIndexOf("<"));
String sufix = srcString.substring(srcString.lastIndexOf("<"));
String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
CTBody makeBody = CTBody.Factory.parse(prefix + mainPart + addPart + sufix);
src1Body.set(makeBody);
return src1Document;
}