SpringBoot整合poi实现Word文件的导出
1、引入Maven依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.16</version>
</dependency>
2、封装WordUtils工具类
import com.hikvision.treasury.cache.FilePathCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
import org.springframework.core.io.ClassPathResource;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
@Slf4j
public class WordUtils {
public static void wordXUtils(Map<String, Object> params, String templatePath, ArrayList<Map<String, String>> listData) {
try {
ClassPathResource fileResource = new ClassPathResource("file/templateFile/非库管人员入库登记簿.docx");
InputStream is = fileResource.getInputStream();
XWPFDocument doc = new XWPFDocument(is);
replaceInPara(doc, params);
insertInTable(doc, listData);
File directory = new File("");
String tempFile = directory.getAbsolutePath()+"\\"+ Math.random() +".docx";
log.info("获取临时文件存储的路径:" + tempFile);
FilePathCache.tempPath.add(tempFile);
OutputStream os = new FileOutputStream(tempFile);
doc.write(os);
close(os);
close(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static XWPFDocument mergeWord(XWPFDocument document, XWPFDocument doucDocument2) {
XWPFDocument src1Document = document;
CTBody src1Body = src1Document.getDocument().getBody();
XWPFDocument src2Document = doucDocument2;
CTBody src2Body = src2Document.getDocument().getBody();
XmlOptions optionsOuter = new XmlOptions();
optionsOuter.setSaveOuter();
String appendString = src2Body.xmlText(optionsOuter);
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 = null;