083c3dd408fc6533ba5a4e68b482bd583eed53c2.svn-base 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. package cn.com.goldenwater.dcproj.utils;
  2. import org.apache.poi.ooxml.POIXMLDocument;
  3. import org.apache.poi.openxml4j.opc.OPCPackage;
  4. import org.apache.poi.xwpf.usermodel.*;
  5. import java.io.*;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.util.ArrayList;
  9. import java.util.Iterator;
  10. import java.util.List;
  11. import java.util.Map;
  12. public class OfficeUtil {
  13. /**
  14. * 根据指定的参数值、模板,生成 word 文档
  15. *
  16. * @param param 需要替换的变量
  17. * @param template 模板
  18. */
  19. public static CustomXWPFDocument generateWord(Map<String, Object> param, String template) {
  20. CustomXWPFDocument doc = null;
  21. try {
  22. OPCPackage pack = POIXMLDocument.openPackage(template);
  23. doc = new CustomXWPFDocument(pack);
  24. if (param != null && param.size() > 0) {
  25. //处理段落
  26. List<XWPFParagraph> paragraphList = doc.getParagraphs();
  27. processParagraphs(paragraphList, param, doc);
  28. //处理表格
  29. Iterator<XWPFTable> it = doc.getTablesIterator();
  30. while (it.hasNext()) {
  31. XWPFTable table = it.next();
  32. List<XWPFTableRow> rows = table.getRows();
  33. for (XWPFTableRow row : rows) {
  34. List<XWPFTableCell> cells = row.getTableCells();
  35. for (XWPFTableCell cell : cells) {
  36. List<XWPFParagraph> paragraphListTable = cell.getParagraphs();
  37. processParagraphs(paragraphListTable, param, doc);
  38. }
  39. }
  40. }
  41. }
  42. } catch (Exception e) {
  43. e.printStackTrace();
  44. }
  45. return doc;
  46. }
  47. /**
  48. * 处理段落
  49. *
  50. * @param paragraphList
  51. */
  52. public static void processParagraphs(List<XWPFParagraph> paragraphList, Map<String, Object> param, CustomXWPFDocument doc) {
  53. if (paragraphList != null && paragraphList.size() > 0) {
  54. for (XWPFParagraph paragraph : paragraphList) {
  55. //poi转换过来的行间距过大,需要手动调整
  56. if (paragraph.getSpacingBefore() >= 1000 || paragraph.getSpacingAfter() > 1000) {
  57. paragraph.setSpacingBefore(0);
  58. paragraph.setSpacingAfter(0);
  59. }
  60. //设置word中左右间距
  61. paragraph.setIndentationLeft(0);
  62. paragraph.setIndentationRight(0);
  63. List<XWPFRun> runs = paragraph.getRuns();
  64. //加了图片,修改了paragraph的runs的size,所以循环不能使用runs
  65. List<XWPFRun> allRuns = new ArrayList<XWPFRun>(runs);
  66. for (XWPFRun run : allRuns) {
  67. String text = run.getText(0);
  68. if (text != null) {
  69. boolean isSetText = false;
  70. for (Map.Entry<String, Object> entry : param.entrySet()) {
  71. String key = entry.getKey();
  72. if (text.indexOf(key) != -1) {
  73. isSetText = true;
  74. Object value = entry.getValue();
  75. if (value instanceof String) {//文本替换
  76. text = text.replace(key, value.toString());
  77. } else if (value instanceof Map) {//图片替换
  78. text = text.replace(key, "");
  79. Map pic = (Map) value;
  80. int width = Integer.parseInt(pic.get("width").toString());
  81. int height = Integer.parseInt(pic.get("height").toString());
  82. int picType = getPictureType(pic.get("type").toString());
  83. byte[] byteArray = (byte[]) pic.get("content");
  84. ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
  85. try {
  86. String blipId = doc.addPictureData(byteInputStream, picType);
  87. doc.createPicture(blipId, doc.getNextPicNameNumber(picType), width, height, paragraph);
  88. } catch (Exception e) {
  89. e.printStackTrace();
  90. }
  91. }
  92. }
  93. }
  94. if (isSetText) {
  95. run.setText(text, 0);
  96. }
  97. }
  98. }
  99. }
  100. }
  101. }
  102. /**
  103. * 根据图片类型,取得对应的图片类型代码
  104. *
  105. * @param picType
  106. * @return int
  107. */
  108. private static int getPictureType(String picType) {
  109. int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
  110. if (picType != null) {
  111. if ("png".equalsIgnoreCase(picType)) {
  112. res = CustomXWPFDocument.PICTURE_TYPE_PNG;
  113. } else if ("dib".equalsIgnoreCase(picType)) {
  114. res = CustomXWPFDocument.PICTURE_TYPE_DIB;
  115. } else if ("emf".equalsIgnoreCase(picType)) {
  116. res = CustomXWPFDocument.PICTURE_TYPE_EMF;
  117. } else if ("jpg".equalsIgnoreCase(picType) || "jpeg".equalsIgnoreCase(picType)) {
  118. res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
  119. } else if ("wmf".equalsIgnoreCase(picType)) {
  120. res = CustomXWPFDocument.PICTURE_TYPE_WMF;
  121. }
  122. }
  123. return res;
  124. }
  125. /**
  126. * 将输入流中的数据写入字节数组
  127. *
  128. * @param in
  129. * @return
  130. */
  131. public static byte[] inputStream2ByteArray(InputStream in, boolean isClose) {
  132. byte[] byteArray = null;
  133. try {
  134. int total = in.available();
  135. byteArray = new byte[total];
  136. in.read(byteArray);
  137. } catch (IOException e) {
  138. e.printStackTrace();
  139. } finally {
  140. if (isClose) {
  141. try {
  142. in.close();
  143. } catch (Exception e2) {
  144. System.out.println("关闭流失败");
  145. }
  146. }
  147. }
  148. return byteArray;
  149. }
  150. public static byte[] getFileStream(String url) {
  151. try {
  152. url = url.replace("\\", "/");
  153. System.out.println(url);
  154. URL httpUrl = new URL(url);
  155. HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
  156. conn.setRequestMethod("GET");
  157. conn.setConnectTimeout(1 * 1000);
  158. InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
  159. byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
  160. return btImg;
  161. } catch (Exception e) {
  162. e.printStackTrace();
  163. }
  164. return null;
  165. }
  166. /**
  167. * 网络图片进行下载,本地图片直接从文件下读取
  168. */
  169. public static InputStream retFileStream(String url, String uploadPath) {
  170. try {
  171. if (url.startsWith("http")) {
  172. url = url.replace("\\", "/");
  173. URL httpUrl = new URL(url);
  174. HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
  175. conn.setRequestMethod("GET");
  176. conn.setConnectTimeout(1 * 1000);
  177. InputStream inStream = conn.getInputStream();
  178. return inStream;
  179. } else {
  180. File file = new File(uploadPath + url);
  181. if (file.isFile()) {
  182. InputStream inStream = new FileInputStream(file);
  183. return inStream;
  184. }
  185. }
  186. } catch (Exception e) {
  187. e.printStackTrace();
  188. }
  189. return null;
  190. }
  191. public static byte[] readInputStream(InputStream inStream) throws Exception {
  192. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  193. byte[] buffer = new byte[1024];
  194. int len = 0;
  195. while ((len = inStream.read(buffer)) != -1) {
  196. outStream.write(buffer, 0, len);
  197. }
  198. inStream.close();
  199. return outStream.toByteArray();
  200. }
  201. }