1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > JAVA根据word模版使用poi导出word文档 包含图片 文字

JAVA根据word模版使用poi导出word文档 包含图片 文字

时间:2018-11-25 13:59:58

相关推荐

JAVA根据word模版使用poi导出word文档 包含图片 文字

模版word文件,内容和表格都已处理,保留了字体和样式,图片可以指定大小,docx类型的模版字段有问题的话,整个字段复制进去即可,不要手敲${}

生成的word文件

/*** word工具类** @author lks* @date /2/24 11:16*/public class WordUtils {//本地测试/*** 模版图片规则:${img-上传图片-200-200} * img:代表是图片* 上传图片:模版的字段* 200:宽(像素),可自定义* 200:高(像素),可自定义*/public static void main(String[] args) throws IOException {//docx本地Map<String, Object> map = new HashMap<>();map.put("姓名", "张三");map.put("上传图片", "https://smart-form-dev.oss-cn-/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"));//doc 本地,doc暂时不支持图片,只能做到文本替换// Map<String, Object> map = new HashMap<>();// map.put("姓名", "张三");// map.put("上传图片", "https://smart-form-dev.oss-cn-/fillImg/150a3d39976ab324/1632644009526_%E5%9B%BE%E7%89%871.png");// FileInputStream in = new FileInputStream("/Users/liangkesai/Downloads/1.docx");// 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()));// }// doc.write(new FileOutputStream("/Users/liangkesai/Downloads/4.doc"));}/*** 下载** @param templateUrl* @param map* @param response* @param fileName*/public static void downWordByTemplate(String templateUrl, Map<String, Object> map, HttpServletResponse response, String fileName) {//输出流OutputStream os = null;InputStream in = null;try {// 生成word文档并读取模板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();}}}/*** 替换文字和图片** @param paragraphs* @param map*/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)) {// 图片规则,${img-上传图片-200-200} img-字段名-宽-高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);}}}}}}/*** 根据图片类型,取得对应的图片类型代码** @param picType* @return int*/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;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。