模版word文件,内容和表格都已处理,保留了字体和样式,图片可以指定大小,docx类型的模版字段有问题的话,整个字段复制进去即可,不要手敲${}
生成的word文件
public class WordUtils {
public static void main(String[] args) throws IOException {
Map<String, Object> map = new HashMap<>();
map.put("姓名", "张三");
map.put("上传图片", "https://smart-form-dev.oss-cn-beijing.aliyuncs.com/fillImg/150a3d39976ab324/1632644009526_%E5%9B%BE%E7%89%871.png");
FileInputStream in = new FileInputStream("/Users/liangkesai/Downloads/1.docx");
XWPFDocument docx = new XWPFDocument(in);
Iterator<XWPFTable> itTable = docx.getTablesIterator();
while (itTable.hasNext()) {
List<XWPFTableRow> rows = itTable.next().getRows();
for (XWPFTableRow row : rows) {
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
if (cell != null) {
processParagraphs(cell.getParagraphs(), map);
}
}
}
}
processParagraphs(docx.getParagraphs(), map);
docx.write(new FileOutputStream("/Users/liangkesai/Downloads/4.doc"));
}
public static void downWordByTemplate(String templateUrl, Map<String, Object> map, HttpServletResponse response, String fileName) {
OutputStream os = null;
InputStream in = null;
try {
in = new URL(templateUrl).openStream();
if (!templateUrl.endsWith("doc") && !templateUrl.endsWith("docx")) {
throw new CustomException("文件类型错误");
}
if (templateUrl.endsWith("doc")) {
HWPFDocument doc = new HWPFDocument(in);
Range range = doc.getRange();
for (Map.Entry entry : map.entrySet()) {
String key = "${" + entry.getKey() + "}";
range.replaceText(key, String.valueOf(entry.getValue()));
}
fileName = fileName + ".doc";
response.reset();
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
os = response.getOutputStream();
doc.write(os);
doc.close();
} else {
XWPFDocument docx = new XWPFDocument(in);
Iterator<XWPFTable> itTable = docx.getTablesIterator();
while (itTable.hasNext()) {
List<XWPFTableRow> rows = itTable.next().getRows();
for (XWPFTableRow row : rows) {
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
if (cell != null) {
processParagraphs(cell.getParagraphs(), map);
}
}
}
}
processParagraphs(docx.getParagraphs(), map);
fileName = fileName + ".docx";
response.reset();
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
os = response.getOutputStream();
docx.write(os);
docx.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
protected static void processParagraphs(List<XWPFParagraph> paragraphs, Map<String, Object> map) {
for (XWPFParagraph paragraph : paragraphs) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String textTemp = StrUtil.subBetween(run.getText(run.getTextPosition()), "${", "}");
if (StrUtil.isNotBlank(textTemp)) {
if (textTemp.startsWith("img-")) {
String[] split = textTemp.split("-");
if (split.length == 4 && StrUtil.isNotBlank(split[1]) && map.containsKey(split[1])) {
try {
String imgurl = String.valueOf(map.get(split[1]));
String picType = null;
if (imgurl.contains(".")) {
picType = imgurl.substring(imgurl.lastIndexOf(".") + 1);
}
byte[] bs = IOUtils.toByteArray(new URL(imgurl).openStream());
int width = Units.toEMU(Double.parseDouble(split[2]));
int height = Units.toEMU(Double.parseDouble(split[3]));
run.setText("", 0);
run.addPicture(new ByteArrayInputStream(bs), getPictureType(picType), "", width, height);
} catch (IOException | InvalidFormatException e) {
run.setText(String.valueOf(map.get(split[1])), 0);
}
}
} else {
if (map.containsKey(textTemp)) {
run.setText(String.valueOf(map.get(textTemp)), 0);
}
}
}
}
}
}
private static int getPictureType(String picType) {
int res = Document.PICTURE_TYPE_JPEG;
if (picType != null) {
if (picType.equalsIgnoreCase("png")) {
res = Document.PICTURE_TYPE_PNG;
} else if (picType.equalsIgnoreCase("dib")) {
res = Document.PICTURE_TYPE_DIB;
} else if (picType.equalsIgnoreCase("emf")) {
res = Document.PICTURE_TYPE_EMF;
} else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
res = Document.PICTURE_TYPE_JPEG;
} else if (picType.equalsIgnoreCase("wmf")) {
res = Document.PICTURE_TYPE_WMF;
} else {
res = Document.PICTURE_TYPE_JPEG;
}
}
return res;
}