关键词搜索

源码搜索 ×
×

Java使用Apache POI导出-注意前端不要使用Ajax异步请求

发布2017-06-27浏览3034次

详情内容

Java使用Apache POI导出-注意前端不要使用Ajax异步请求,如果你想弹出文件下载框,请勿使用异步下载。

Apahce POI pom配置

  1. <!--EXCEL导入导出 -->
  2. <dependency>
  3. <groupId>org.apache.poi</groupId>
  4. <artifactId>poi</artifactId>
  5. <version>3.9</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.apache.poi</groupId>
  9. <artifactId>poi-ooxml</artifactId>
  10. <version>3.9</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.apache.poi</groupId>
  14. <artifactId>poi-ooxml-schemas</artifactId>
  15. <version>3.9</version>
  16. </dependency>

 

ExoportExcelUtil

  1. package com.boonya.common.utils.excel;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.InputStream;
  5. import java.lang.reflect.InvocationTargetException;
  6. import java.lang.reflect.Method;
  7. import java.util.ArrayList;
  8. import java.util.Arrays;
  9. import java.util.Date;
  10. import java.util.List;
  11. import java.util.Map;
  12. import javax.servlet.http.HttpServletResponse;
  13. import org.apache.poi.hssf.usermodel.HSSFCell;
  14. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  15. import org.apache.poi.hssf.usermodel.HSSFRichTextString;
  16. import org.apache.poi.hssf.usermodel.HSSFRow;
  17. import org.apache.poi.hssf.usermodel.HSSFSheet;
  18. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  19. import org.apache.poi.hssf.util.CellRangeAddress;
  20. import org.apache.poi.xssf.usermodel.XSSFCell;
  21. import org.apache.poi.xssf.usermodel.XSSFCellStyle;
  22. import org.apache.poi.xssf.usermodel.XSSFRichTextString;
  23. import org.apache.poi.xssf.usermodel.XSSFRow;
  24. import org.apache.poi.xssf.usermodel.XSSFSheet;
  25. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  26. import com.cvnavi.common.utils.DateUtil;
  27. @SuppressWarnings("deprecation")
  28. public class ExportExcelUtil {
  29. public static String getFileName() {
  30. return DateUtil.toString(new Date(), "yyyyMMdd-HHmmss");
  31. }
  32. public static XSSFWorkbook getWorkbook(List<?> resultList, String[] showName, String[] resourceField,
  33. Class<?> resultObj, Map<String, Map<String, String>> formatMap) throws SecurityException,
  34. NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
  35. XSSFWorkbook workbook = new XSSFWorkbook();
  36. XSSFSheet sheet = workbook.createSheet("sheet1");
  37. sheet.setDefaultColumnWidth((short) 20);
  38. XSSFCellStyle centerStyle = workbook.createCellStyle();// 设置为水平居中
  39. centerStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
  40. centerStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
  41. XSSFRow row;
  42. XSSFCell cell;
  43. createTitle(showName, sheet);
  44. // 下面是输出各行的数据 下面是输出各行的数据 下面是输出各行的
  45. for (int i = 0, len = resultList.size(); i < len; i++) {
  46. Object result = resultList.get(i);
  47. row = sheet.createRow(i + 1);
  48. // 创建第 i+1 行
  49. for (int j = 0; j < resourceField.length; j++) {
  50. cell = row.createCell(j);// 创建第 j 列
  51. Method method;
  52. method = resultObj.getMethod(resourceField[j]);
  53. // 这里用到了反射机制,通 这里用到了反射机制, 这里用到了反射机制 过方法名来取得对应方法返回的结果对象
  54. Object obj = method.invoke(result);
  55. if (obj != null) {
  56. if (formatMap != null && formatMap.containsKey(resourceField)) {
  57. cell.setCellValue(formatMap.get(resourceField).get(obj.toString()));
  58. } else {
  59. cell.setCellValue(obj.toString());
  60. }
  61. }
  62. }
  63. }
  64. return workbook;
  65. }
  66. /**
  67. *
  68. * @Title: getWorkbook2 @Description: TODO(创建HSSFWorkbook) @param
  69. * resultList @param showName @param resourceField @param resultObj @param
  70. * formatMap @return @throws SecurityException @throws
  71. * NoSuchMethodException @throws IllegalArgumentException @throws
  72. * IllegalAccessException @throws InvocationTargetException 设定文件 @return
  73. * HSSFWorkbook 返回类型 @author: pengjl @date 2017年6月27日 下午3:22:51 @throws
  74. */
  75. public static HSSFWorkbook getWorkbook2(List<?> resultList, String[] showName, String[] resourceField,
  76. Class<?> resultObj, Map<String, Map<String, String>> formatMap) throws SecurityException,
  77. NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
  78. HSSFWorkbook workbook = new HSSFWorkbook();
  79. HSSFSheet sheet = workbook.createSheet("sheet1");
  80. sheet.setDefaultColumnWidth((short) 20);
  81. HSSFCellStyle centerStyle = workbook.createCellStyle();// 设置为水平居中
  82. centerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  83. centerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  84. HSSFRow row;
  85. HSSFCell cell;
  86. createTitle2(showName, sheet);
  87. // 下面是输出各行的数据 下面是输出各行的数据 下面是输出各行的
  88. for (int i = 0; i < resultList.size(); i++) {
  89. Object result = resultList.get(i);
  90. row = sheet.createRow(i + 1);
  91. // 创建第 i+1 行
  92. for (int j = 0; j < resourceField.length; j++) {
  93. cell = row.createCell(j);// 创建第 j 列
  94. Method method;
  95. method = resultObj.getMethod(resourceField[j]);
  96. // 这里用到了反射机制,通 这里用到了反射机制, 这里用到了反射机制 过方法名来取得对应方法返回的结果对象
  97. Object obj = method.invoke(result);
  98. if (obj != null) {
  99. if (formatMap != null && formatMap.containsKey(resourceField)) {
  100. cell.setCellValue(formatMap.get(resourceField).get(obj.toString()));
  101. } else {
  102. cell.setCellValue(obj.toString());
  103. }
  104. }
  105. }
  106. }
  107. return workbook;
  108. }
  109. /**
  110. * @Title: createTitle2 @Description: TODO(多行表头) @param showName @param
  111. * sheet 设定文件 @return void 返回类型 @author: pengjl @date 2017年6月27日
  112. * 下午3:23:30 @throws
  113. */
  114. private static void createTitle2(String[] showName, HSSFSheet sheet) {
  115. HSSFRow row = sheet.createRow(0); // 创建第 1 行,也就是输出表头 创建第
  116. HSSFCell cell;
  117. for (int i = 0; i < showName.length; i++) {
  118. cell = row.createCell(i);
  119. // 创建第 i 列 创建第
  120. cell.setCellValue(new HSSFRichTextString(showName[i]));
  121. }
  122. }
  123. private static void createTitle(String[] showName, XSSFSheet sheet) {
  124. XSSFRow row = sheet.createRow(0); // 创建第 1 行,也就是输出表头 创建第
  125. XSSFCell cell;
  126. for (int i = 0; i < showName.length; i++) {
  127. cell = row.createCell(i);
  128. // 创建第 i 列 创建第
  129. cell.setCellValue(new XSSFRichTextString(showName[i]));
  130. }
  131. }
  132. /**
  133. * @Title: createWorkbook @Description: TODO(创建HSSFWorkbook) @param
  134. * resultList @param showName @return 设定文件 @return HSSFWorkbook
  135. * 返回类型 @author: pengjl @date 2017年6月27日 下午3:23:41 @throws
  136. */
  137. public static HSSFWorkbook createWorkbook(List<List<Cell>> resultList, String[] showName) {
  138. HSSFWorkbook workbook = new HSSFWorkbook();
  139. HSSFSheet sheet = workbook.createSheet("sheet1");
  140. HSSFCellStyle centerStyle = workbook.createCellStyle();// 设置为水平居中
  141. centerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  142. centerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  143. createTitle2(showName, sheet);
  144. HSSFRow row = null;
  145. HSSFCell cell = null;
  146. int[][] arraSort;
  147. if (resultList.size() == 0) {
  148. arraSort = new int[0][0];
  149. } else {
  150. arraSort = new int[resultList.get(0).size()][resultList.size()];
  151. }
  152. for (int i = 0; i < resultList.size(); i++) {
  153. row = sheet.createRow(i + 1);
  154. // sheet.setColumnWidth(i + 1, 15);
  155. List<Cell> cellList = resultList.get(i);
  156. for (int j = 0; j < cellList.size(); j++) {
  157. cell = row.createCell(j);// 创建第 j 列
  158. cell.setCellValue(cellList.get(j).getValue());
  159. int b = cell.getStringCellValue().getBytes().length;
  160. arraSort[j][i] = b;
  161. if (cellList.get(j).getStyle() != null) {
  162. cell.setCellStyle(cellList.get(j).getStyle());
  163. }
  164. }
  165. }
  166. // 列的最大列宽值(不包括标题)
  167. int widthInfo[] = TwoMaxInfo(arraSort);
  168. // 与标题在比较列宽
  169. for (int i = 0; i < showName.length; i++) {
  170. // sheet.autoSizeColumn(i);
  171. // 算出列(包括标题的最大列宽)
  172. int maxWidthInfo = showName[i].getBytes().length > widthInfo[i] ? showName[i].getBytes().length
  173. : widthInfo[i];
  174. sheet.setColumnWidth(i, maxWidthInfo * 256);
  175. }
  176. return workbook;
  177. }
  178. public static int[] TwoMaxInfo(int[][] arraSort) {
  179. int[] arraySortInfo = null;
  180. arraySortInfo = new int[arraSort.length];
  181. int count = 0;
  182. for (int[] is : arraSort) {
  183. int[] arraInfo = is;
  184. Arrays.sort(arraInfo);
  185. arraySortInfo[count] = arraInfo[arraInfo.length - 1];
  186. count++;
  187. }
  188. return arraySortInfo;
  189. }
  190. /**
  191. * @Title: createWorkbookAll @Description: TODO(创建HSSFWorkbook) @param
  192. * vMap @param showName @return 设定文件 @return HSSFWorkbook 返回类型 @author:
  193. * pengjl @date 2017年6月27日 下午3:20:04 @throws
  194. */
  195. public static HSSFWorkbook createWorkbookAll(Map<String, List<List<Cell>>> vMap, String[] showName) {
  196. HSSFWorkbook workbook = new HSSFWorkbook();
  197. for (Map.Entry<String, List<List<Cell>>> entry : vMap.entrySet()) {
  198. HSSFSheet sheet = workbook.createSheet(entry.getKey());
  199. sheet.setDefaultColumnWidth((short) 15);
  200. HSSFCellStyle centerStyle = workbook.createCellStyle();// 设置为水平居中
  201. centerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  202. centerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  203. createTitle2(showName, sheet);
  204. HSSFRow row;
  205. HSSFCell cell;
  206. for (int i = 0; i < entry.getValue().size(); i++) {
  207. row = sheet.createRow(i + 1);
  208. List<Cell> cellList = entry.getValue().get(i);
  209. for (int j = 0; j < cellList.size(); j++) {
  210. cell = row.createCell(j);// 创建第 j 列
  211. cell.setCellValue(cellList.get(j).getValue());
  212. if (cellList.get(j).getStyle() != null) {
  213. cell.setCellStyle(cellList.get(j).getStyle());
  214. }
  215. }
  216. }
  217. for (int i = 0; i < showName.length; i++) {
  218. sheet.autoSizeColumn(i);
  219. }
  220. }
  221. return workbook;
  222. }
  223. /**
  224. * @Title: workbook2InputStream @Description: TODO(导出Excel文件) @param
  225. * workbook @param fileName @param response @return @throws Exception
  226. * 设定文件 @return InputStream 返回类型 @author: pengjl @date 2017年6月27日
  227. * 下午3:20:21 @throws
  228. */
  229. public static InputStream workbook2InputStream(HSSFWorkbook workbook, String fileName, HttpServletResponse response)
  230. throws Exception {
  231. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  232. workbook.write(baos);
  233. baos.flush();
  234. byte[] aa = baos.toByteArray();
  235. InputStream excelStream = new ByteArrayInputStream(aa, 0, aa.length);
  236. response.setContentType("application/vnd.ms-excel;charset=UTF-8");
  237. response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
  238. response.getOutputStream().write(aa);
  239. response.setContentLength(aa.length);
  240. response.getOutputStream().flush();
  241. baos.close();
  242. return excelStream;
  243. }
  244. /**
  245. *
  246. * @Title: workbook2InputStream @Description: TODO(导出Excel文件) @param
  247. * workbook @param fileName @param response @return @throws Exception
  248. * 设定文件 @return InputStream 返回类型 @author: pengjl @date 2017年6月27日
  249. * 下午3:20:49 @throws
  250. */
  251. public static InputStream workbook2InputStream(XSSFWorkbook workbook, String fileName, HttpServletResponse response)
  252. throws Exception {
  253. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  254. workbook.write(baos);
  255. baos.flush();
  256. byte[] aa = baos.toByteArray();
  257. InputStream excelStream = new ByteArrayInputStream(aa, 0, aa.length);
  258. response.setContentType("application/vnd.ms-excel;charset=UTF-8");
  259. response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
  260. response.getOutputStream().write(aa);
  261. response.setContentLength(aa.length);
  262. response.getOutputStream().flush();
  263. baos.close();
  264. return excelStream;
  265. }
  266. /**
  267. * @Title: createWorkbookVarietyParam @Description:
  268. * TODO(创建HSSFWorkbook) @param resultList @param showName @param
  269. * headerName @return 设定文件 @return HSSFWorkbook 返回类型 @author: pengjl @date
  270. * 2017年6月27日 下午3:21:22 @throws
  271. */
  272. public static HSSFWorkbook createWorkbookVarietyParam(ArrayList<ArrayList<String>> resultList, String[] showName,
  273. ArrayList<String> headerName) {
  274. HSSFWorkbook workbook = new HSSFWorkbook();
  275. HSSFSheet sheet = workbook.createSheet("sheet1");
  276. sheet.setDefaultColumnWidth((short) 15);
  277. HSSFCellStyle centerStyle = workbook.createCellStyle();// 设置为水平居中
  278. centerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  279. centerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  280. /**
  281. * 设置表头的样式
  282. */
  283. HSSFCellStyle titylStyle = workbook.createCellStyle();
  284. createTitleVariety(showName, headerName, sheet, titylStyle);
  285. HSSFRow row;
  286. HSSFCell cell;
  287. if (resultList != null && resultList.size() > 0) {
  288. for (int i = 0; i < resultList.size(); i++) {
  289. ArrayList<String> rowResultList = resultList.get(i);
  290. if (headerName != null && headerName.size() > 0) {
  291. row = sheet.createRow((short) (i + 1 + headerName.size()));
  292. } else {
  293. row = sheet.createRow((short) (i + 1));
  294. }
  295. if (rowResultList != null && rowResultList.size() > 0) {
  296. for (int n = 0; n <= rowResultList.size(); n++) {
  297. cell = row.createCell(n);// 创建第 j 列
  298. cell.setCellStyle(centerStyle);
  299. if (n == 0) {
  300. // 为Excel表的第一列添加编号,表头为:序号;eg:1,2,3,4……
  301. cell.setCellValue(i + 1);
  302. } else if (rowResultList.get(n - 1) != null) {
  303. cell.setCellValue(rowResultList.get(n - 1).toString());
  304. } else {
  305. cell.setCellValue("");
  306. }
  307. }
  308. }
  309. }
  310. }
  311. return workbook;
  312. }
  313. /**
  314. * @Title: createTitleVariety @Description: TODO(多行表头) @param
  315. * showName @param headerName @param sheet @param titylStyle 设定文件 @return
  316. * void 返回类型 @author: pengjl @date 2017年6月27日 下午3:24:24 @throws
  317. */
  318. private static void createTitleVariety(String[] showName, ArrayList<String> headerName, HSSFSheet sheet,
  319. HSSFCellStyle titylStyle) {
  320. HSSFRow row;
  321. HSSFCell cell;
  322. titylStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  323. titylStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  324. if (headerName != null && headerName.size() > 0) {
  325. for (int i = 0; i < headerName.size(); i++) {
  326. row = sheet.createRow((short) i);
  327. if (i == 0) {
  328. cell = row.createCell(i);
  329. sheet.addMergedRegion(new CellRangeAddress(i, i, (short) 0, (short) showName.length));
  330. cell.setCellStyle(titylStyle);
  331. if (headerName.get(i) != null) {
  332. cell.setCellValue(new HSSFRichTextString(headerName.get(i).toString()));
  333. } else {
  334. cell.setCellValue(new HSSFRichTextString(""));
  335. }
  336. } else {
  337. cell = row.createCell(i - 1);
  338. sheet.addMergedRegion(new CellRangeAddress(i, i, (short) 0, (short) showName.length));
  339. if (headerName.get(i) != null) {
  340. cell.setCellValue(new HSSFRichTextString(headerName.get(i).toString()));
  341. } else {
  342. cell.setCellValue(new HSSFRichTextString(""));
  343. }
  344. }
  345. }
  346. }
  347. // 设置Excel字段
  348. if (headerName != null && headerName.size() > 0) {
  349. row = sheet.createRow((short) headerName.size());
  350. } else {
  351. row = sheet.createRow(0);
  352. }
  353. for (int n = 0; n <= showName.length; n++) {
  354. if (n == 0) {
  355. cell = row.createCell(n);
  356. cell.setCellStyle(titylStyle);
  357. cell.setCellValue(new HSSFRichTextString("序号"));
  358. } else {
  359. cell = row.createCell(n);
  360. cell.setCellStyle(titylStyle);
  361. cell.setCellValue(new HSSFRichTextString(showName[n - 1]));
  362. }
  363. }
  364. }
  365. }

 

 

 

使用方式

 

  1. /**
  2. * @Title: export
  3. * @Description: TODO(单车导出&&导出前端Ajax请求不会弹出下载文件)
  4. * @param request
  5. * @param response
  6. * @param temperatureBean
  7. * @return 设定文件
  8. * @return String 返回类型
  9. * @author: pengjl
  10. * @date 2017年6月22日 下午8:38:43
  11. * @throws
  12. */
  13. @RequestMapping("/export")
  14. public void export(HttpServletRequest request,HttpServletResponse response,TemperatureBean temperatureBean){
  15. int mapType = Integer.parseInt(request.getParameter("mapType"));
  16. try {
  17. List<TemperatureView> viewList= iTemperatureService.queryTrack(temperatureBean, mapType,true);
  18. String[] showName = {"车牌号","GPS时间","速度(公里/时)","海拔(米)","位置","温度"};
  19. List<List<Cell>> dataList = new ArrayList<List<Cell>>();
  20. List<Cell> cellList = new ArrayList<Cell>();
  21. if(viewList.size()>0){
  22. for (TemperatureView view : viewList) {
  23. cellList = new ArrayList<Cell>();
  24. cellList.add(new Cell(view.getTemperatureList().get(0).getPlateCode()));
  25. cellList.add(new Cell(view.getGpsTime()));
  26. cellList.add(new Cell(Double.parseDouble(view.getTemperatureList().get(0).getSpeed()+"")/10 + ""));
  27. cellList.add(new Cell(view.getTemperatureList().get(0).getHigh()+""));
  28. cellList.add(new Cell(view.getTemperatureList().get(0).getLocation()));
  29. String temp = "" ;
  30. for(TemperatureBean bean: view.getTemperatureList()){
  31. temp += bean.getAppendName()+":" + bean.getTemperature() + bean.getUnit() + "," ;
  32. }
  33. if(!temp.equals(""))
  34. temp = temp.substring(0,temp.length()-1);
  35. cellList.add(new Cell(temp));
  36. dataList.add(cellList);
  37. }
  38. }
  39. String fileName = ExportExcel.getFileName();
  40. ExportExcel.workbook2InputStream(ExportExcel.createWorkbook(dataList, showName), fileName,response);
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. }
  44. }

 

 

 

测试URL

在浏览器中输入导出地址:http://127.0.0.1:8081/cvnavi-monitoryt/temperature/export.do?tokenStr=A2E4CE20DBC8A4EDAC0EC5B2AD25D022&startTime=2017-06-27%2000:00:00&endTime=2017-06-27%2023:59:59&plateCode=%E6%B2%AAAWG102&mapType=2&vehicleId=4427355843467897

通过直接访问可以下载,故推测前端反映的无法导出是因为其使用了Ajax,文件本身是异步方式,所以浏览器不会弹出下载框。

设置文字样式:https://blog.csdn.net/sinat_34093604/article/details/53432545

弹出下载文件:使用超链接或者form表单提交(form表单提交在submit时不想浏览器地址提交需要添加返回return ;空返回

  1. <button class="mini-fs-export-button zs-btn" id="btn_export">导出</button>
  2. <form id="form_export" style="color: white;display: none;" action="../export/zzjgglExport.do" ></form>
  1. $("#form_export").on("submit",function(e){
  2. return ;
  3. });
  4. $("#btn_export").on("click",function(e){
  5. $("#form_export").submit();
  6. });

前端传值给POI导出可参考:https://blog.csdn.net/hhzzcc_/article/details/80419396

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载