1
0

ExcelUtil.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. package com.kmall.common.utils.excel;
  2. import org.apache.commons.lang.StringUtils;
  3. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  4. import org.apache.poi.ss.util.CellRangeAddress;
  5. import org.apache.poi.xssf.usermodel.XSSFRow;
  6. import org.apache.poi.xssf.usermodel.XSSFSheet;
  7. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  8. import org.jxls.reader.ReaderBuilder;
  9. import org.jxls.reader.XLSReader;
  10. import org.springframework.stereotype.Component;
  11. import org.xml.sax.SAXException;
  12. import javax.servlet.ServletOutputStream;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import java.io.*;
  16. import java.net.HttpURLConnection;
  17. import java.net.URL;
  18. import java.net.URLEncoder;
  19. import java.util.List;
  20. import java.util.Map;
  21. import java.util.zip.ZipInputStream;
  22. /**
  23. * 导出EXCEL表格
  24. *
  25. * @author 曾俊
  26. * @create 2017-05-27 10:26
  27. */
  28. @Component
  29. public class ExcelUtil {
  30. /**
  31. * @param
  32. * @return
  33. * @info 写出Excel标题内容
  34. */
  35. public static void exportExcel(String fileName, String[] titles,
  36. List<Map<Integer, String>> lists, HttpServletResponse response, HttpServletRequest request) throws IOException {
  37. XSSFWorkbook xls = new XSSFWorkbook();
  38. XSSFSheet sheet = xls.createSheet("Sheet1");
  39. XSSFRow row = sheet.createRow(0);// 第一行
  40. for (int i = 0; i < titles.length; i++) {
  41. sheet.setColumnWidth(i, (short) 5000);
  42. sheet.setColumnWidth(0, (short) 1300);
  43. row.createCell(i).setCellValue(titles[i]);
  44. }
  45. // 内容
  46. int rowNum = 1; //第二行开始
  47. for (Map<Integer, String> map : lists) {
  48. XSSFRow rowTmp = sheet.createRow(rowNum);
  49. int cols = map.size();
  50. for (int i = 0; i < cols; i++) {
  51. rowTmp.createCell(i).setCellValue(map.get(i));
  52. }
  53. rowNum++;
  54. }
  55. ByteArrayOutputStream os = new ByteArrayOutputStream();
  56. xls.write(os);
  57. byte[] content = os.toByteArray();
  58. InputStream is = new ByteArrayInputStream(content);
  59. //根据浏览器不同,对文件的名字进行不同的编码设置
  60. final String userAgent = request.getHeader("USER-AGENT");
  61. String finalFileName = null;
  62. if (userAgent.contains("MSIE") || userAgent.contains("Trident")) { //IE浏览器
  63. finalFileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
  64. } else if (StringUtils.contains(userAgent, "Mozilla")) { //google,火狐浏览器
  65. finalFileName = new String((fileName + ".xlsx").getBytes("UTF-8"), "ISO-8859-1");
  66. } else {
  67. finalFileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8"); //其他浏览器
  68. }
  69. // 设置response参数,可以打开下载页面
  70. response.reset();
  71. response.setContentType("application/vnd.ms-excel;charset=utf-8");
  72. response.setHeader("Content-Disposition", "attachment;filename="
  73. + finalFileName);
  74. ServletOutputStream out = response.getOutputStream();
  75. BufferedInputStream bis = null;
  76. BufferedOutputStream bos = null;
  77. try {
  78. bis = new BufferedInputStream(is);
  79. bos = new BufferedOutputStream(out);
  80. byte[] buff = new byte[2048];
  81. int bytesRead;
  82. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  83. bos.write(buff, 0, bytesRead);
  84. }
  85. } catch (Exception e) {
  86. e.printStackTrace();
  87. } finally {
  88. if (bis != null)
  89. bis.close();
  90. if (bos != null)
  91. bos.close();
  92. }
  93. os.close();
  94. }
  95. /**
  96. * 导出文件
  97. *
  98. * @param fileName
  99. * @param response
  100. * @param inStream
  101. * @throws Exception
  102. */
  103. public static void exportFile(String fileName, HttpServletResponse response, InputStream inStream) throws Exception {
  104. byte[] data = FileUtil.readInputStream(inStream);
  105. ServletOutputStream os = null;
  106. try {
  107. os = response.getOutputStream();
  108. response.setContentType("application/octet-stream ");
  109. response.setHeader("Connection", "close"); // 表示不能用浏览器直接打开
  110. response.setHeader("Accept-Ranges", "bytes");// 告诉客户端允许断点续传多线程连接下载
  111. response.setHeader("Content-Disposition",
  112. "attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO8859-1"));
  113. response.setCharacterEncoding("UTF-8");
  114. os.write(data);
  115. } catch (IOException e) {
  116. throw e;
  117. } finally {
  118. if (inStream != null)
  119. inStream.close();
  120. }
  121. os.close();
  122. }
  123. /**
  124. * 读取导入excel
  125. *
  126. * @param name
  127. * @param beans
  128. * @param in
  129. * @throws InvalidFormatException
  130. * @throws SAXException
  131. * @throws IOException
  132. */
  133. public void readExcel(String name, Map<String, Object> beans, InputStream in) throws InvalidFormatException, SAXException, IOException {
  134. InputStream inputXML = null;
  135. InputStream inputXLS = null;
  136. try {
  137. inputXML = new BufferedInputStream(this.getClass().getResourceAsStream(name));
  138. XLSReader mainReader = ReaderBuilder.buildFromXML(inputXML);
  139. inputXLS = new BufferedInputStream(in);
  140. mainReader.read(inputXLS, beans);
  141. } catch (Exception e) {
  142. throw e;
  143. } finally {
  144. if (inputXML != null) {
  145. inputXML.close();
  146. }
  147. if (inputXLS != null) {
  148. inputXLS.close();
  149. }
  150. }
  151. }
  152. /**
  153. * 读取导入excel 只用于ZipInputStream 因为ZipInputStream不能在这个时候关闭
  154. *
  155. * @param name
  156. * @param beans
  157. * @param in
  158. * @throws InvalidFormatException
  159. * @throws SAXException
  160. * @throws IOException
  161. */
  162. public void readZipExcel(String name, Map<String, Object> beans, ZipInputStream in) throws InvalidFormatException, SAXException, IOException {
  163. InputStream inputXML = null;
  164. InputStream inputXLS = null;
  165. try {
  166. inputXML = new BufferedInputStream(this.getClass().getResourceAsStream(name));
  167. XLSReader mainReader = ReaderBuilder.buildFromXML(inputXML);
  168. inputXLS = new BufferedInputStream(in);
  169. mainReader.read(in, beans);
  170. } catch (Exception e) {
  171. throw e;
  172. } finally {
  173. // if (inputXML != null) {
  174. // inputXML.close();
  175. // }
  176. }
  177. }
  178. /**
  179. * @desc 拿到图片OSS路径转换为流
  180. * @author 曾俊
  181. * @create 2017/7/25 0025 17:31
  182. **/
  183. public static InputStream getInputStream(String path) throws IOException {
  184. InputStream inputStream = null;
  185. HttpURLConnection httpURLConnection = null;
  186. try {
  187. URL url = new URL(path);
  188. if (url != null) {
  189. httpURLConnection = (HttpURLConnection) url.openConnection();
  190. httpURLConnection.setConnectTimeout(3000);
  191. httpURLConnection.setRequestMethod("GET");
  192. int responseCode = httpURLConnection.getResponseCode();
  193. if (responseCode == 200) {
  194. inputStream = httpURLConnection.getInputStream();
  195. }
  196. }
  197. } catch (Exception e) {
  198. e.printStackTrace();
  199. throw e;
  200. }
  201. return inputStream;
  202. }
  203. /**
  204. * @param
  205. * @return
  206. * @info 写出Excel标题内容
  207. */
  208. public static void exportFormatExcel(String fileName, String[] titles,String width[],
  209. List<Map<Integer, String>> lists, HttpServletResponse response, HttpServletRequest request) throws IOException {
  210. XSSFWorkbook xls = new XSSFWorkbook();
  211. XSSFSheet sheet = xls.createSheet("Sheet1");
  212. XSSFRow row = sheet.createRow(0);// 第一行
  213. row.setHeight((short)600);
  214. for (int i = 0; i < titles.length; i++) {
  215. row.createCell(i).setCellValue(titles[i]);
  216. sheet.setColumnWidth(i, Integer.valueOf(width[i]));
  217. }
  218. if(lists.size()>1){//合并单元格
  219. sheet.addMergedRegion(new CellRangeAddress(1,lists.size(),8,8));
  220. sheet.addMergedRegion(new CellRangeAddress(1,lists.size(),9,9));
  221. sheet.addMergedRegion(new CellRangeAddress(1,lists.size(),10,10));
  222. }
  223. // 内容
  224. int rowNum = 1; //第二行开始
  225. for (Map<Integer, String> map : lists) {
  226. XSSFRow rowTmp = sheet.createRow(rowNum);
  227. int cols = map.size();
  228. for (int i = 0; i < cols; i++) {
  229. rowTmp.createCell(i).setCellValue(map.get(i));
  230. }
  231. rowNum++;
  232. }
  233. ByteArrayOutputStream os = new ByteArrayOutputStream();
  234. xls.write(os);
  235. byte[] content = os.toByteArray();
  236. InputStream is = new ByteArrayInputStream(content);
  237. //根据浏览器不同,对文件的名字进行不同的编码设置
  238. final String userAgent = request.getHeader("USER-AGENT");
  239. String finalFileName = null;
  240. if (userAgent.contains("MSIE") || userAgent.contains("Trident")) { //IE浏览器
  241. finalFileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8");
  242. } else if (StringUtils.contains(userAgent, "Mozilla")) { //google,火狐浏览器
  243. finalFileName = new String((fileName + ".xlsx").getBytes("UTF-8"), "ISO-8859-1");
  244. } else {
  245. finalFileName = URLEncoder.encode(fileName + ".xlsx", "UTF-8"); //其他浏览器
  246. }
  247. // 设置response参数,可以打开下载页面
  248. response.reset();
  249. response.setContentType("application/vnd.ms-excel;charset=utf-8");
  250. response.setHeader("Content-Disposition", "attachment;filename="
  251. + finalFileName);
  252. ServletOutputStream out = response.getOutputStream();
  253. BufferedInputStream bis = null;
  254. BufferedOutputStream bos = null;
  255. try {
  256. bis = new BufferedInputStream(is);
  257. bos = new BufferedOutputStream(out);
  258. byte[] buff = new byte[2048];
  259. int bytesRead;
  260. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  261. bos.write(buff, 0, bytesRead);
  262. }
  263. } catch (Exception e) {
  264. e.printStackTrace();
  265. } finally {
  266. if (bis != null)
  267. bis.close();
  268. if (bos != null)
  269. bos.close();
  270. }
  271. os.close();
  272. }
  273. }