Maven项目结合POI导出Excl表格

一、POM文件添加依赖

  1. <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
  2. <dependency>
  3. <groupId>org.apache.poi</groupId>
  4. <artifactId>poi</artifactId>
  5. <version>3.6</version>
  6. </dependency>

二、将ExportExcel类放进项目的util中

  1. package com.jonychen.util.core;
  2.  
  3. import org.apache.poi.hssf.usermodel.*;
  4. import org.apache.poi.hssf.util.HSSFColor;
  5. import org.apache.poi.ss.util.CellRangeAddress;
  6.  
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.IOException;
  9. import java.io.OutputStream;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12.  
  13. import static com.jonychen.HttpKit.getResponse;(后面有代码,复制粘贴即可)
  14. /**
  15. *导出工具类
  16. */
  17. public class ExportExcel{
  18.  
  19. //显示的导出表的标题
  20. private String title;
  21. //导出表的列名
  22. private String[] rowName ;
  23.  
  24. private List<Object[]> dataList = new ArrayList<Object[]>();
  25.  
  26. HttpServletResponse response;
  27.  
  28. //构造方法,传入要导出的数据
  29. public ExportExcel(String title,String[] rowName,List<Object[]> dataList){
  30. this.dataList = dataList;
  31. this.rowName = rowName;
  32. this.title = title;
  33. }
  34.  
  35. /*
  36. * 导出数据
  37. * */
  38. public void export() throws Exception{
  39. try{
  40. HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
  41. HSSFSheet sheet = workbook.createSheet(title); // 创建工作表
  42.  
  43. // 产生表格标题行
  44. HSSFRow rowm = sheet.createRow(0);
  45. HSSFCell cellTiltle = rowm.createCell(0);
  46.  
  47. //sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
  48. HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
  49. HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象
  50.  
  51. sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));
  52. cellTiltle.setCellStyle(columnTopStyle);
  53. cellTiltle.setCellValue(title);
  54.  
  55. // 定义所需列数
  56. int columnNum = rowName.length;
  57. HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)
  58.  
  59. // 将列头设置到sheet的单元格中
  60. for(int n=0;n<columnNum;n++){
  61. HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格
  62. cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型
  63. HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
  64. cellRowName.setCellValue(text); //设置列头单元格的值
  65. cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
  66. }
  67.  
  68. //将查询出的数据设置到sheet对应的单元格中
  69. for(int i=0;i<dataList.size();i++){
  70.  
  71. Object[] obj = dataList.get(i);//遍历每个对象
  72. HSSFRow row = sheet.createRow(i+3);//创建所需的行数
  73.  
  74. for(int j=0; j<obj.length; j++){
  75. HSSFCell cell = null; //设置单元格的数据类型
  76. if(j == 0){
  77. cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
  78. cell.setCellValue(i+1);
  79. }else{
  80. cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
  81. if(!"".equals(obj[j]) && obj[j] != null){
  82. cell.setCellValue(obj[j].toString()); //设置单元格的值
  83. }
  84. }
  85. cell.setCellStyle(style); //设置单元格样式
  86. }
  87. }
  88. //让列宽随着导出的列长自动适应
  89. for (int colNum = 0; colNum < columnNum; colNum++) {
  90. int columnWidth = sheet.getColumnWidth(colNum) / 256;
  91. for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
  92. HSSFRow currentRow;
  93. //当前行未被使用过
  94. if (sheet.getRow(rowNum) == null) {
  95. currentRow = sheet.createRow(rowNum);
  96. } else {
  97. currentRow = sheet.getRow(rowNum);
  98. }
  99. if (currentRow.getCell(colNum) != null) {
  100. HSSFCell currentCell = currentRow.getCell(colNum);
  101. if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
  102. int length = currentCell.getStringCellValue().getBytes().length;
  103. if (columnWidth < length) {
  104. columnWidth = length;
  105. }
  106. }
  107. }
  108. }
  109. if(colNum == 0){
  110. sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
  111. }else{
  112. sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
  113. }
  114. }
  115.  
  116. if(workbook !=null){
  117. try
  118. {
  119. String fileName = "Excel-Signup" + System.currentTimeMillis() + ".xls";
  120. String headStr = "attachment; filename=\"" + fileName + "\"";
  121. response =getResponse();
  122. response.setContentType("APPLICATION/OCTET-STREAM");
  123. response.setHeader("Content-Disposition", headStr);
  124. OutputStream out = response.getOutputStream();
  125. workbook.write(out);
  126. }
  127. catch (IOException e)
  128. {
  129. e.printStackTrace();
  130. }
  131. }
  132.  
  133. }catch(Exception e){
  134. e.printStackTrace();
  135. }
  136.  
  137. }
  138.  
  139. /*
  140. * 列头单元格样式
  141. */
  142. public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
  143.  
  144. // 设置字体
  145. HSSFFont font = workbook.createFont();
  146. //设置字体大小
  147. font.setFontHeightInPoints((short)11);
  148. //字体加粗
  149. font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  150. //设置字体名字
  151. font.setFontName("Courier New");
  152. //设置样式;
  153. HSSFCellStyle style = workbook.createCellStyle();
  154. //设置底边框;
  155. style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  156. //设置底边框颜色;
  157. style.setBottomBorderColor(HSSFColor.BLACK.index);
  158. //设置左边框;
  159. style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  160. //设置左边框颜色;
  161. style.setLeftBorderColor(HSSFColor.BLACK.index);
  162. //设置右边框;
  163. style.setBorderRight(HSSFCellStyle.BORDER_THIN);
  164. //设置右边框颜色;
  165. style.setRightBorderColor(HSSFColor.BLACK.index);
  166. //设置顶边框;
  167. style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  168. //设置顶边框颜色;
  169. style.setTopBorderColor(HSSFColor.BLACK.index);
  170. //在样式用应用设置的字体;
  171. style.setFont(font);
  172. //设置自动换行;
  173. style.setWrapText(false);
  174. //设置水平对齐的样式为居中对齐;
  175. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  176. //设置垂直对齐的样式为居中对齐;
  177. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  178.  
  179. return style;
  180.  
  181. }
  182.  
  183. /*
  184. * 列数据信息单元格样式
  185. */
  186. public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
  187. // 设置字体
  188. HSSFFont font = workbook.createFont();
  189. //设置字体大小
  190. //font.setFontHeightInPoints((short)10);
  191. //字体加粗
  192. //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  193. //设置字体名字
  194. font.setFontName("Courier New");
  195. //设置样式;
  196. HSSFCellStyle style = workbook.createCellStyle();
  197. //设置底边框;
  198. style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  199. //设置底边框颜色;
  200. style.setBottomBorderColor(HSSFColor.BLACK.index);
  201. //设置左边框;
  202. style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  203. //设置左边框颜色;
  204. style.setLeftBorderColor(HSSFColor.BLACK.index);
  205. //设置右边框;
  206. style.setBorderRight(HSSFCellStyle.BORDER_THIN);
  207. //设置右边框颜色;
  208. style.setRightBorderColor(HSSFColor.BLACK.index);
  209. //设置顶边框;
  210. style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  211. //设置顶边框颜色;
  212. style.setTopBorderColor(HSSFColor.BLACK.index);
  213. //在样式用应用设置的字体;
  214. style.setFont(font);
  215. //设置自动换行;
  216. style.setWrapText(false);
  217. //设置水平对齐的样式为居中对齐;
  218. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  219. //设置垂直对齐的样式为居中对齐;
  220. style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  221.  
  222. return style;
  223.  
  224. }
  225. }
  1. com.jonychen.HttpKit.getResponse
  1. /**
  2. * Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
  3. * <p>
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. * <p>
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. * <p>
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.jonychen.util.core;
  17.  
  18. import org.springframework.web.context.request.RequestContextHolder;
  19. import org.springframework.web.context.request.ServletRequestAttributes;
  20.  
  21. import javax.servlet.http.HttpServletRequest;
  22. import javax.servlet.http.HttpServletResponse;
  23. import java.io.BufferedReader;
  24. import java.io.IOException;
  25. import java.io.InputStreamReader;
  26. import java.io.PrintWriter;
  27. import java.net.URL;
  28. import java.net.URLConnection;
  29. import java.util.Enumeration;
  30. import java.util.HashMap;
  31. import java.util.List;
  32. import java.util.Map;
  33.  
  34. public class HttpKit {
  35.  
  36. public static String getIp(){
  37. return HttpKit.getRequest().getRemoteHost();
  38. }
  39.  
  40. /**
  41. * 获取所有请求的值
  42. */
  43. public static Map<String, String> getRequestParameters() {
  44. HashMap<String, String> values = new HashMap<>();
  45. HttpServletRequest request = HttpKit.getRequest();
  46. Enumeration enums = request.getParameterNames();
  47. while ( enums.hasMoreElements()){
  48. String paramName = (String) enums.nextElement();
  49. String paramValue = request.getParameter(paramName);
  50. values.put(paramName, paramValue);
  51. }
  52. return values;
  53. }
  54.  
  55. /**
  56. * 获取 HttpServletRequest
  57. */
  58. public static HttpServletResponse getResponse() {
  59. HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
  60. return response;
  61. }
  62.  
  63. /**
  64. * 获取 包装防Xss Sql注入的 HttpServletRequest
  65. * @return request
  66. */
  67. public static HttpServletRequest getRequest() {
  68. HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  69. return new WafRequestWrapper(request);
  70. }
  71.  
  72. /**
  73. * 向指定URL发送GET方法的请求
  74. *
  75. * @param url 发送请求的URL
  76. * @param param 请求参数
  77. * @return URL 所代表远程资源的响应结果
  78. */
  79. public static String sendGet(String url, Map<String, String> param) {
  80. String result = "";
  81. BufferedReader in = null;
  82. try {
  83. String para = "";
  84. for (String key : param.keySet()) {
  85. para += (key + "=" + param.get(key) + "&");
  86. }
  87. if (para.lastIndexOf("&") > 0) {
  88. para = para.substring(0, para.length() - 1);
  89. }
  90. String urlNameString = url + "?" + para;
  91. URL realUrl = new URL(urlNameString);
  92. // 打开和URL之间的连接
  93. URLConnection connection = realUrl.openConnection();
  94. // 设置通用的请求属性
  95. connection.setRequestProperty("accept", "*/*");
  96. connection.setRequestProperty("connection", "Keep-Alive");
  97. connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  98. // 建立实际的连接
  99. connection.connect();
  100. // 获取所有响应头字段
  101. Map<String, List<String>> map = connection.getHeaderFields();
  102. // 遍历所有的响应头字段
  103. //for (String key : map.keySet()) {
  104. // System.out.println(key + "--->" + map.get(key));
  105. //}
  106. // 定义 BufferedReader输入流来读取URL的响应
  107. in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  108. String line;
  109. while ((line = in.readLine()) != null) {
  110. result += line;
  111. }
  112. } catch (Exception e) {
  113. System.out.println("发送GET请求出现异常!" + e);
  114. e.printStackTrace();
  115. }
  116. // 使用finally块来关闭输入流
  117. finally {
  118. try {
  119. if (in != null) {
  120. in.close();
  121. }
  122. } catch (Exception e2) {
  123. e2.printStackTrace();
  124. }
  125. }
  126. return result;
  127. }
  128.  
  129. /**
  130. * 向指定 URL 发送POST方法的请求
  131. *
  132. * @param url 发送请求的 URL
  133. * @param param 请求参数
  134. * @return 所代表远程资源的响应结果
  135. */
  136. public static String sendPost(String url, Map<String, String> param) {
  137. PrintWriter out = null;
  138. BufferedReader in = null;
  139. String result = "";
  140. try {
  141. String para = "";
  142. for (String key : param.keySet()) {
  143. para += (key + "=" + param.get(key) + "&");
  144. }
  145. if (para.lastIndexOf("&") > 0) {
  146. para = para.substring(0, para.length() - 1);
  147. }
  148. String urlNameString = url + "?" + para;
  149. URL realUrl = new URL(urlNameString);
  150. // 打开和URL之间的连接
  151. URLConnection conn = realUrl.openConnection();
  152. // 设置通用的请求属性
  153. conn.setRequestProperty("accept", "*/*");
  154. conn.setRequestProperty("connection", "Keep-Alive");
  155. conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  156. // 发送POST请求必须设置如下两行
  157. conn.setDoOutput(true);
  158. conn.setDoInput(true);
  159. // 获取URLConnection对象对应的输出流
  160. out = new PrintWriter(conn.getOutputStream());
  161. // 发送请求参数
  162. out.print(param);
  163. // flush输出流的缓冲
  164. out.flush();
  165. // 定义BufferedReader输入流来读取URL的响应
  166. in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  167. String line;
  168. while ((line = in.readLine()) != null) {
  169. result += line;
  170. }
  171. } catch (Exception e) {
  172. System.out.println("发送 POST 请求出现异常!" + e);
  173. e.printStackTrace();
  174. }
  175. // 使用finally块来关闭输出流、输入流
  176. finally {
  177. try {
  178. if (out != null) {
  179. out.close();
  180. }
  181. if (in != null) {
  182. in.close();
  183. }
  184. } catch (IOException ex) {
  185. ex.printStackTrace();
  186. }
  187. }
  188. return result;
  189. }
  190.  
  191. }
  1.  

三、项目中写Controller逻辑层进行调用工具类导出即可

  1. @RequestMapping(value = "/export",method = {RequestMethod.GET, RequestMethod.POST})
  2. @ResponseBody
  3. @ApiOperation(value = "导出报表", httpMethod = "GET", notes = "导出报表,前端写一个导出地址调用此接口即可")
  4. public void signupExport(HttpServletRequest request, HttpServletResponse response) throws Exception {
  5. //获取数据
  6. List<SignupInfo> list = signupService.getSignupList();
  7. logger.info("获取全部列表数据"+JSONArray.toJSON(list));
  8.  
  9. String title = "汇总表";
  10. String[] rowsName = new String[]{"序号", "姓名", "性别","手机号码", "单位名称", "省", "备注"};
  11. List<Object[]> dataList = new ArrayList<>();
  12. Object[] objs = null;
  13. for (int i = 0; i < list.size(); i++) {
  14. SignupfdfdsInfo signupInfo= list.get(i);
  15. objs = new Object[rowsName.length];
  16. objs[0] = signupInfo.getId();
  17. objs[1] = signupInfo.getUserName();
  18. objs[2] = signupInfo.getSex();
  19. objs[3]=signupInfo.getMobile();
  20. objs[4] = signupInfo.getCompany();
  21. objs[5] = signupInfo.getProvince();
  22. objs[6] = signupInfo.getRemark();
  23. dataList.add(objs);
  24. }
  25. ExportExcel ex = new ExportExcel(title, rowsName, dataList);
  26. ex.export();
  27. }

可能遇到的异常:NPE(原因:导出的数据中没有值,数据库中存的值都要有默认值,我varchar型存的是无,int型的是0)

Maven项目结合POI导出Excl表格Demo-亲测可用的更多相关文章

  1. 解决Eclipse左键无法查看maven第三方包的源代码,多图亲测可用【转】

    Debug进不了的原因及解决办法: 一.ctrl+左键点击没有找到你的源码 1.先设置maven 2.通过maven下Jar包源码 选中总包目录下的pom.xml-->右键-->Run A ...

  2. Maven项目结合POI实现导入导入导入导入导入Excl表格Demo-亲测可用

    第一步:写入maven依赖(3.6是比较稳定的版本,可用于生产环境) <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --& ...

  3. poi导出word表格详解 超详细了

    转:非常感谢原作者 poi导出word表格详解 2018年07月20日 10:41:33 Z丶royAl 阅读数:36138   一.效果如下 二.js代码 function export_word( ...

  4. java中使用poi导出excel表格数据并且可以手动修改导出路径

    在我们开发项目中,很多时候会提出这样的需求:将前端的某某数据以excel表格导出,今天就给大家写一个简单的模板. 这里我们选择使用poi导出excel: 第一步:导入需要的jar包到 lib 文件夹下

  5. 使用poi导出Excel表格,jar包冲突

    HTTP Status 500 – Internal Server Error Type Exception Report Message Handler processing failed; nes ...

  6. 复杂的POI导出Excel表格(多行表头、合并单元格)

    poi导出excel有两种方式: 第一种:从无到有的创建整个excel,通过HSSFWorkbook,HSSFSheet HSSFCell, 等对象一步一步的创建出工作簿,sheet,和单元格,并添加 ...

  7. poi导出word表格跨行

    DataCommon.java package com.ksource.pwlp.model.statistic; public class DataCommon { private Long id; ...

  8. Strust2+POI导出exel表格且解决文件名中文乱码/不显示

    下载并导入项目[poi.3.17.jar] strust.xml <action name="returnLate_*" class="com.stureturnl ...

  9. windows下的java项目打jar分别编写在windows与linux下运行的脚本( 本人亲测可用!)

    前言: 最近公司做了一个工具,要将这个工具打包成一个可运行的程序,编写start.bat和start.sh在windows和linux下都可以运行. 在网上找了很多资料,最后终于找到一个可靠的资料,记 ...

随机推荐

  1. javascript函数笔记

    函数是一个具有特定功能的语句块.函数的定义使用关键字 function,语法如下: function funcName ([parameters]){ statements; [return表达式;] ...

  2. Openstack关于Regions和Availability Zones

    在AWS中有Region和Availability Zones的概念,并且在openstack中也实现了两者,只是不太容易看出来. 此文主要介绍他们的概念和关系,以及在openstack中的实现. 如 ...

  3. zstuoj 4245 KI的斐波那契

    KI的斐波那契 Time Limit: 1 Sec  Memory Limit: 128 MB Submit: 550  Solved: 208 Description KI十分喜欢美丽而优雅的斐波那 ...

  4. hdu dp 1257 最小拦截系统

    最少拦截系统 Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Submit Statu ...

  5. Redis学习篇(四)之List类型及其操作

    Redis的List是一个双向链表 LPUSH 作用:向列表左端添加元素 语法:LPUSH key value value... 从左到右逐个添加到左端,前面的先添加, 可以一次添加多个元素 RPUS ...

  6. luoguP3239 [HNOI2015]亚瑟王 概率期望DP

    当初怎么想的来着.....又忘了...... 首先,总期望 = 每张卡片的期望之和 求期望,只要我们求出每张卡片被用掉的概率即可 如果直接上状态$f[i][j]$表示在第$i$轮中,第$j$张牌发动的 ...

  7. 37.递推:Pell数列

    总时间限制: 3000ms 内存限制: 65536kB 描述 Pell数列a1, a2, a3, ...的定义是这样的,a1 = 1, a2 = 2, ... , an = 2 * an − 1 + ...

  8. extjs用iframe的问题

    项目中用extjs做前提系统的界面是左边用树做目录 右边用tabpanel做内容展示点击树节点的时候 在tabpanel添加新的tab JScript code var newTab = center ...

  9. linux下使用crontab创建定时任务

    在linux中启动crontab服务: /etc/init.d/crond start crontab的命令格式 crontab -l 显示当前的crontab 文件(默认编写的crontab文件会保 ...

  10. 自定义的tabBarController的几种方法

    本文转载自:http://blog.sina.com.cn/s/blog_79c5bdc30100t88i.html 我自己实现的一种可以很方便的实现更换TabBarController图片的方法,代 ...