系统导出功能,多条数据分别导出word,多个word打包到一个zip进行导出,直接拷贝过去可用,如果缺包自行查找。
参考: Java使用word模板导出word_java根据模板导出word-CSDN博客.
@Action(value = "exportToWordZip")
public String exportToWordZip() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
WordUtil xwpfTUtil = null;
FileOutputStream os = null;
InputStream is = null;
List<String> files = new ArrayList<>();
for (int i = 0; i < 2; i++) {
//导出的数据处理
Map<String, Object> params = new HashMap<>();
params.put("${Name}", "Fisher3652");
params.put("${Sex}", "男");
params.put("${Desc}", "18岁\tJAVA开发\r熟悉JVM基本原理");
params.put("${@Pic}", "C:\\Users\\admin\\Desktop\\资源\\32.png");
//获取模版
is = FileUtil.class.getClassLoader().getResourceAsStream("static/letterWordDemo.docx");
xwpfTUtil = new WordUtil();
CustomXWPFDocument doc;
doc = new CustomXWPFDocument(is);
//模版替换成真实数据
xwpfTUtil.replaceInPara(doc, params);
xwpfTUtil.replaceInTable(doc, params);
//生成word到临时文件
String realPath = request.getSession().getServletContext().getRealPath("/");
String parentPath = new File(realPath).getParent() + "/exportToWordZipTemp" ;
File dir = new File(parentPath);
if (!dir.exists()) {
dir.mkdirs();
}
String fileName = parentPath + "/" + i + ".docx";
System.out.println(fileName);
os = new FileOutputStream(fileName);
files.add(fileName);
doc.write(os);
System.out.println("word成功生成");
}
xwpfTUtil.close(os);
xwpfTUtil.close(is);
os.flush();
os.close();
writeZip(files, "文件汇总");
return null;
}
package com.dazhi.itp.util.exportWord;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
import java.io.IOException;
import java.io.InputStream;
public class CustomXWPFDocument extends XWPFDocument {
public CustomXWPFDocument(InputStream in) throws IOException {
super(in);
}
public CustomXWPFDocument(OPCPackage pkg) throws IOException {
super(pkg);
}
public void createPicture(String blipId,int id, int width, int height, XWPFParagraph paragraph)
{
final int EMU = 9525;
width *= EMU;
height *= EMU;
//给段落插入图片
CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();
String picXml = "" +
"<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +
" <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
" <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
" <pic:nvPicPr>" +
" <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" +
" <pic:cNvPicPr/>" +
" </pic:nvPicPr>" +
" <pic:blipFill>" +
" <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" +
" <a:stretch>" +
" <a:fillRect/>" +
" </a:stretch>" +
" </pic:blipFill>" +
" <pic:spPr>" +
" <a:xfrm>" +
" <a:off x=\"0\" y=\"0\"/>" +
" <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" +
" </a:xfrm>" +
" <a:prstGeom prst=\"rect\">" +
" <a:avLst/>" +
" </a:prstGeom>" +
" </pic:spPr>" +
" </pic:pic>" +
" </a:graphicData>" +
"</a:graphic>";
XmlToken xmlToken = null;
try
{
xmlToken = XmlToken.Factory.parse(picXml);
}
catch(XmlException xe)
{
xe.printStackTrace();
}
inline.set(xmlToken);
inline.setDistT(0);
inline.setDistB(0);
inline.setDistL(0);
inline.setDistR(0);
CTPositiveSize2D extent = inline.addNewExtent();
extent.setCx(width);
extent.setCy(height);
CTNonVisualDrawingProps docPr = inline.addNewDocPr();
docPr.setId(id);
docPr.setName("Picture " + id);
docPr.setDescr("Generated");
}
}
package com.dazhi.itp.util.exportWord;
import com.dazhi.itp.util.exportWord.CustomXWPFDocument;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.*;
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;
public class WordUtil {
/**
* 替换段落里面的变量
*
* @param doc 要替换的文档
* @param params 参数
* @throws FileNotFoundException
* @throws InvalidFormatException
*/
public void replaceInPara(CustomXWPFDocument doc, Map<String, Object> params) throws InvalidFormatException, FileNotFoundException {
Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
XWPFParagraph para;
while (iterator.hasNext()) {
para = iterator.next();
this.replaceInPara(para, params,doc);
}
}
/**
* 替换段落里面的变量
* 文本用${}标识,例如${Name},图片用${@},多一个@标识
* @param para 要替换的段落
* @param params 参数
* @throws FileNotFoundException
* @throws InvalidFormatException
*/
public void replaceInPara(XWPFParagraph para, Map<String, Object> params, CustomXWPFDocument doc) throws InvalidFormatException, FileNotFoundException {
List<XWPFRun> runs;
Matcher matcher;
if (this.matcher(para.getParagraphText()).find()) {
runs = para.getRuns();
int start = -1;
int end = -1;
String str = "";
String text= "";
for (int i = 0; i < runs.size(); i++) {
text += runs.get(i).toString();
}
for (int i = 0; i < runs.size(); i++) {
XWPFRun run = runs.get(i);
// System.out.println("------>>>>>>>>>" + text);
if (text.contains("$")) {
start = text.indexOf("$");
}
if ((start != -1)) {
str += text.substring(text.indexOf("$"), text.length()).trim();
String paraList=runs.toString();
// System.out.println("未删除前"+paraList);
Object[] runArr = runs.toArray();
int size=runs.size();
int $Index=0;
for (int j = 0; j < runArr.length; j++) {
if (runArr[j].toString().contains("$")) {
$Index=j;
break;
}
}
int startIn=$Index;
while (startIn<runs.size()) {
para.removeRun(startIn);
// System.out.println("删除中"+para.getRuns());
}
// System.out.println("删除后"+para.getRuns());
}
if ('}' == text.charAt(text.length() - 1)) {
if (start != -1) {
end = text.length() - 1;
break;
}
}
}
// System.out.println("start--->"+start);
// System.out.println("end--->"+end);
// System.out.println("str---->>>" + str);
for (String key : params.keySet()) {
if (str.equals(key)) {
//判断是图片还是文本
if(str.indexOf("@")==-1){
String value= params.get(key).toString();
para.createRun().setText(value);
break;
}else{
//图片处理
String value= params.get(key).toString();
int length = para.getRuns().size();
if (length > 0) {
for (int i = (length - 1); i >= 0; i--) {
para.removeRun(i);
}
}
String blipId = doc.addPictureData(new FileInputStream(new File(value)), CustomXWPFDocument.PICTURE_TYPE_PNG);
doc.createPicture(blipId,doc.getNextPicNameNumber(CustomXWPFDocument.PICTURE_TYPE_PNG), 550, 250,para);
break;
}
}
}
}
}
/**
* 替换表格里面的变量
*
* @param doc 要替换的文档
* @param params 参数
* @throws FileNotFoundException
* @throws InvalidFormatException
*/
public void replaceInTable(CustomXWPFDocument doc, Map<String, Object> params) throws InvalidFormatException, FileNotFoundException {
Iterator<XWPFTable> iterator = doc.getTablesIterator();
XWPFTable table;
List<XWPFTableRow> rows;
List<XWPFTableCell> cells;
List<XWPFParagraph> paras;
while (iterator.hasNext()) {
table = iterator.next();
rows = table.getRows();
for (XWPFTableRow row : rows) {
cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
paras = cell.getParagraphs();
for (XWPFParagraph para : paras) {
this.replaceInPara(para, params,doc);
}
}
}
}
}
/**
* 正则匹配字符串
*
* @param str
* @return
*/
private Matcher matcher(String str) {
Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher;
}
/**
* 关闭输入流
*
* @param is
*/
public void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 关闭输出流
*
* @param os
*/
public void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
模版