Maven项目结合POI导出Excl表格Demo-亲测可用
Maven项目结合POI导出Excl表格
一、POM文件添加依赖
- <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi</artifactId>
- <version>3.6</version>
- </dependency>
二、将ExportExcel类放进项目的util中
- package com.jonychen.util.core;
- import org.apache.poi.hssf.usermodel.*;
- import org.apache.poi.hssf.util.HSSFColor;
- import org.apache.poi.ss.util.CellRangeAddress;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.util.ArrayList;
- import java.util.List;
- import static com.jonychen.HttpKit.getResponse;(后面有代码,复制粘贴即可)
- /**
- *导出工具类
- */
- public class ExportExcel{
- //显示的导出表的标题
- private String title;
- //导出表的列名
- private String[] rowName ;
- private List<Object[]> dataList = new ArrayList<Object[]>();
- HttpServletResponse response;
- //构造方法,传入要导出的数据
- public ExportExcel(String title,String[] rowName,List<Object[]> dataList){
- this.dataList = dataList;
- this.rowName = rowName;
- this.title = title;
- }
- /*
- * 导出数据
- * */
- public void export() throws Exception{
- try{
- HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
- HSSFSheet sheet = workbook.createSheet(title); // 创建工作表
- // 产生表格标题行
- HSSFRow rowm = sheet.createRow(0);
- HSSFCell cellTiltle = rowm.createCell(0);
- //sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
- HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
- HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象
- sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));
- cellTiltle.setCellStyle(columnTopStyle);
- cellTiltle.setCellValue(title);
- // 定义所需列数
- int columnNum = rowName.length;
- HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)
- // 将列头设置到sheet的单元格中
- for(int n=0;n<columnNum;n++){
- HSSFCell cellRowName = rowRowName.createCell(n); //创建列头对应个数的单元格
- cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型
- HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
- cellRowName.setCellValue(text); //设置列头单元格的值
- cellRowName.setCellStyle(columnTopStyle); //设置列头单元格样式
- }
- //将查询出的数据设置到sheet对应的单元格中
- for(int i=0;i<dataList.size();i++){
- Object[] obj = dataList.get(i);//遍历每个对象
- HSSFRow row = sheet.createRow(i+3);//创建所需的行数
- for(int j=0; j<obj.length; j++){
- HSSFCell cell = null; //设置单元格的数据类型
- if(j == 0){
- cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
- cell.setCellValue(i+1);
- }else{
- cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
- if(!"".equals(obj[j]) && obj[j] != null){
- cell.setCellValue(obj[j].toString()); //设置单元格的值
- }
- }
- cell.setCellStyle(style); //设置单元格样式
- }
- }
- //让列宽随着导出的列长自动适应
- for (int colNum = 0; colNum < columnNum; colNum++) {
- int columnWidth = sheet.getColumnWidth(colNum) / 256;
- for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
- HSSFRow currentRow;
- //当前行未被使用过
- if (sheet.getRow(rowNum) == null) {
- currentRow = sheet.createRow(rowNum);
- } else {
- currentRow = sheet.getRow(rowNum);
- }
- if (currentRow.getCell(colNum) != null) {
- HSSFCell currentCell = currentRow.getCell(colNum);
- if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
- int length = currentCell.getStringCellValue().getBytes().length;
- if (columnWidth < length) {
- columnWidth = length;
- }
- }
- }
- }
- if(colNum == 0){
- sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
- }else{
- sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
- }
- }
- if(workbook !=null){
- try
- {
- String fileName = "Excel-Signup" + System.currentTimeMillis() + ".xls";
- String headStr = "attachment; filename=\"" + fileName + "\"";
- response =getResponse();
- response.setContentType("APPLICATION/OCTET-STREAM");
- response.setHeader("Content-Disposition", headStr);
- OutputStream out = response.getOutputStream();
- workbook.write(out);
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- /*
- * 列头单元格样式
- */
- public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
- // 设置字体
- HSSFFont font = workbook.createFont();
- //设置字体大小
- font.setFontHeightInPoints((short)11);
- //字体加粗
- font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
- //设置字体名字
- font.setFontName("Courier New");
- //设置样式;
- HSSFCellStyle style = workbook.createCellStyle();
- //设置底边框;
- style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
- //设置底边框颜色;
- style.setBottomBorderColor(HSSFColor.BLACK.index);
- //设置左边框;
- style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
- //设置左边框颜色;
- style.setLeftBorderColor(HSSFColor.BLACK.index);
- //设置右边框;
- style.setBorderRight(HSSFCellStyle.BORDER_THIN);
- //设置右边框颜色;
- style.setRightBorderColor(HSSFColor.BLACK.index);
- //设置顶边框;
- style.setBorderTop(HSSFCellStyle.BORDER_THIN);
- //设置顶边框颜色;
- style.setTopBorderColor(HSSFColor.BLACK.index);
- //在样式用应用设置的字体;
- style.setFont(font);
- //设置自动换行;
- style.setWrapText(false);
- //设置水平对齐的样式为居中对齐;
- style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
- //设置垂直对齐的样式为居中对齐;
- style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
- return style;
- }
- /*
- * 列数据信息单元格样式
- */
- public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
- // 设置字体
- HSSFFont font = workbook.createFont();
- //设置字体大小
- //font.setFontHeightInPoints((short)10);
- //字体加粗
- //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
- //设置字体名字
- font.setFontName("Courier New");
- //设置样式;
- HSSFCellStyle style = workbook.createCellStyle();
- //设置底边框;
- style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
- //设置底边框颜色;
- style.setBottomBorderColor(HSSFColor.BLACK.index);
- //设置左边框;
- style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
- //设置左边框颜色;
- style.setLeftBorderColor(HSSFColor.BLACK.index);
- //设置右边框;
- style.setBorderRight(HSSFCellStyle.BORDER_THIN);
- //设置右边框颜色;
- style.setRightBorderColor(HSSFColor.BLACK.index);
- //设置顶边框;
- style.setBorderTop(HSSFCellStyle.BORDER_THIN);
- //设置顶边框颜色;
- style.setTopBorderColor(HSSFColor.BLACK.index);
- //在样式用应用设置的字体;
- style.setFont(font);
- //设置自动换行;
- style.setWrapText(false);
- //设置水平对齐的样式为居中对齐;
- style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
- //设置垂直对齐的样式为居中对齐;
- style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
- return style;
- }
- }
- com.jonychen.HttpKit.getResponse
- /**
- * Copyright (c) 2015-2016, Chill Zhuang 庄骞 (smallchill@163.com).
- * <p>
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- package com.jonychen.util.core;
- import org.springframework.web.context.request.RequestContextHolder;
- import org.springframework.web.context.request.ServletRequestAttributes;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.Enumeration;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- public class HttpKit {
- public static String getIp(){
- return HttpKit.getRequest().getRemoteHost();
- }
- /**
- * 获取所有请求的值
- */
- public static Map<String, String> getRequestParameters() {
- HashMap<String, String> values = new HashMap<>();
- HttpServletRequest request = HttpKit.getRequest();
- Enumeration enums = request.getParameterNames();
- while ( enums.hasMoreElements()){
- String paramName = (String) enums.nextElement();
- String paramValue = request.getParameter(paramName);
- values.put(paramName, paramValue);
- }
- return values;
- }
- /**
- * 获取 HttpServletRequest
- */
- public static HttpServletResponse getResponse() {
- HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
- return response;
- }
- /**
- * 获取 包装防Xss Sql注入的 HttpServletRequest
- * @return request
- */
- public static HttpServletRequest getRequest() {
- HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
- return new WafRequestWrapper(request);
- }
- /**
- * 向指定URL发送GET方法的请求
- *
- * @param url 发送请求的URL
- * @param param 请求参数
- * @return URL 所代表远程资源的响应结果
- */
- public static String sendGet(String url, Map<String, String> param) {
- String result = "";
- BufferedReader in = null;
- try {
- String para = "";
- for (String key : param.keySet()) {
- para += (key + "=" + param.get(key) + "&");
- }
- if (para.lastIndexOf("&") > 0) {
- para = para.substring(0, para.length() - 1);
- }
- String urlNameString = url + "?" + para;
- URL realUrl = new URL(urlNameString);
- // 打开和URL之间的连接
- URLConnection connection = realUrl.openConnection();
- // 设置通用的请求属性
- connection.setRequestProperty("accept", "*/*");
- connection.setRequestProperty("connection", "Keep-Alive");
- connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
- // 建立实际的连接
- connection.connect();
- // 获取所有响应头字段
- Map<String, List<String>> map = connection.getHeaderFields();
- // 遍历所有的响应头字段
- //for (String key : map.keySet()) {
- // System.out.println(key + "--->" + map.get(key));
- //}
- // 定义 BufferedReader输入流来读取URL的响应
- in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- String line;
- while ((line = in.readLine()) != null) {
- result += line;
- }
- } catch (Exception e) {
- System.out.println("发送GET请求出现异常!" + e);
- e.printStackTrace();
- }
- // 使用finally块来关闭输入流
- finally {
- try {
- if (in != null) {
- in.close();
- }
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- return result;
- }
- /**
- * 向指定 URL 发送POST方法的请求
- *
- * @param url 发送请求的 URL
- * @param param 请求参数
- * @return 所代表远程资源的响应结果
- */
- public static String sendPost(String url, Map<String, String> param) {
- PrintWriter out = null;
- BufferedReader in = null;
- String result = "";
- try {
- String para = "";
- for (String key : param.keySet()) {
- para += (key + "=" + param.get(key) + "&");
- }
- if (para.lastIndexOf("&") > 0) {
- para = para.substring(0, para.length() - 1);
- }
- String urlNameString = url + "?" + para;
- URL realUrl = new URL(urlNameString);
- // 打开和URL之间的连接
- URLConnection conn = realUrl.openConnection();
- // 设置通用的请求属性
- conn.setRequestProperty("accept", "*/*");
- conn.setRequestProperty("connection", "Keep-Alive");
- conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
- // 发送POST请求必须设置如下两行
- conn.setDoOutput(true);
- conn.setDoInput(true);
- // 获取URLConnection对象对应的输出流
- out = new PrintWriter(conn.getOutputStream());
- // 发送请求参数
- out.print(param);
- // flush输出流的缓冲
- out.flush();
- // 定义BufferedReader输入流来读取URL的响应
- in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
- String line;
- while ((line = in.readLine()) != null) {
- result += line;
- }
- } catch (Exception e) {
- System.out.println("发送 POST 请求出现异常!" + e);
- e.printStackTrace();
- }
- // 使用finally块来关闭输出流、输入流
- finally {
- try {
- if (out != null) {
- out.close();
- }
- if (in != null) {
- in.close();
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- return result;
- }
- }
三、项目中写Controller逻辑层进行调用工具类导出即可
- @RequestMapping(value = "/export",method = {RequestMethod.GET, RequestMethod.POST})
- @ResponseBody
- @ApiOperation(value = "导出报表", httpMethod = "GET", notes = "导出报表,前端写一个导出地址调用此接口即可")
- public void signupExport(HttpServletRequest request, HttpServletResponse response) throws Exception {
- //获取数据
- List<SignupInfo> list = signupService.getSignupList();
- logger.info("获取全部列表数据"+JSONArray.toJSON(list));
- String title = "汇总表";
- String[] rowsName = new String[]{"序号", "姓名", "性别","手机号码", "单位名称", "省", "备注"};
- List<Object[]> dataList = new ArrayList<>();
- Object[] objs = null;
- for (int i = 0; i < list.size(); i++) {
- SignupfdfdsInfo signupInfo= list.get(i);
- objs = new Object[rowsName.length];
- objs[0] = signupInfo.getId();
- objs[1] = signupInfo.getUserName();
- objs[2] = signupInfo.getSex();
- objs[3]=signupInfo.getMobile();
- objs[4] = signupInfo.getCompany();
- objs[5] = signupInfo.getProvince();
- objs[6] = signupInfo.getRemark();
- dataList.add(objs);
- }
- ExportExcel ex = new ExportExcel(title, rowsName, dataList);
- ex.export();
- }
可能遇到的异常:NPE(原因:导出的数据中没有值,数据库中存的值都要有默认值,我varchar型存的是无,int型的是0)
Maven项目结合POI导出Excl表格Demo-亲测可用的更多相关文章
- 解决Eclipse左键无法查看maven第三方包的源代码,多图亲测可用【转】
Debug进不了的原因及解决办法: 一.ctrl+左键点击没有找到你的源码 1.先设置maven 2.通过maven下Jar包源码 选中总包目录下的pom.xml-->右键-->Run A ...
- Maven项目结合POI实现导入导入导入导入导入Excl表格Demo-亲测可用
第一步:写入maven依赖(3.6是比较稳定的版本,可用于生产环境) <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --& ...
- poi导出word表格详解 超详细了
转:非常感谢原作者 poi导出word表格详解 2018年07月20日 10:41:33 Z丶royAl 阅读数:36138 一.效果如下 二.js代码 function export_word( ...
- java中使用poi导出excel表格数据并且可以手动修改导出路径
在我们开发项目中,很多时候会提出这样的需求:将前端的某某数据以excel表格导出,今天就给大家写一个简单的模板. 这里我们选择使用poi导出excel: 第一步:导入需要的jar包到 lib 文件夹下
- 使用poi导出Excel表格,jar包冲突
HTTP Status 500 – Internal Server Error Type Exception Report Message Handler processing failed; nes ...
- 复杂的POI导出Excel表格(多行表头、合并单元格)
poi导出excel有两种方式: 第一种:从无到有的创建整个excel,通过HSSFWorkbook,HSSFSheet HSSFCell, 等对象一步一步的创建出工作簿,sheet,和单元格,并添加 ...
- poi导出word表格跨行
DataCommon.java package com.ksource.pwlp.model.statistic; public class DataCommon { private Long id; ...
- Strust2+POI导出exel表格且解决文件名中文乱码/不显示
下载并导入项目[poi.3.17.jar] strust.xml <action name="returnLate_*" class="com.stureturnl ...
- windows下的java项目打jar分别编写在windows与linux下运行的脚本( 本人亲测可用!)
前言: 最近公司做了一个工具,要将这个工具打包成一个可运行的程序,编写start.bat和start.sh在windows和linux下都可以运行. 在网上找了很多资料,最后终于找到一个可靠的资料,记 ...
随机推荐
- javascript函数笔记
函数是一个具有特定功能的语句块.函数的定义使用关键字 function,语法如下: function funcName ([parameters]){ statements; [return表达式;] ...
- Openstack关于Regions和Availability Zones
在AWS中有Region和Availability Zones的概念,并且在openstack中也实现了两者,只是不太容易看出来. 此文主要介绍他们的概念和关系,以及在openstack中的实现. 如 ...
- zstuoj 4245 KI的斐波那契
KI的斐波那契 Time Limit: 1 Sec Memory Limit: 128 MB Submit: 550 Solved: 208 Description KI十分喜欢美丽而优雅的斐波那 ...
- hdu dp 1257 最小拦截系统
最少拦截系统 Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u Submit Statu ...
- Redis学习篇(四)之List类型及其操作
Redis的List是一个双向链表 LPUSH 作用:向列表左端添加元素 语法:LPUSH key value value... 从左到右逐个添加到左端,前面的先添加, 可以一次添加多个元素 RPUS ...
- luoguP3239 [HNOI2015]亚瑟王 概率期望DP
当初怎么想的来着.....又忘了...... 首先,总期望 = 每张卡片的期望之和 求期望,只要我们求出每张卡片被用掉的概率即可 如果直接上状态$f[i][j]$表示在第$i$轮中,第$j$张牌发动的 ...
- 37.递推:Pell数列
总时间限制: 3000ms 内存限制: 65536kB 描述 Pell数列a1, a2, a3, ...的定义是这样的,a1 = 1, a2 = 2, ... , an = 2 * an − 1 + ...
- extjs用iframe的问题
项目中用extjs做前提系统的界面是左边用树做目录 右边用tabpanel做内容展示点击树节点的时候 在tabpanel添加新的tab JScript code var newTab = center ...
- linux下使用crontab创建定时任务
在linux中启动crontab服务: /etc/init.d/crond start crontab的命令格式 crontab -l 显示当前的crontab 文件(默认编写的crontab文件会保 ...
- 自定义的tabBarController的几种方法
本文转载自:http://blog.sina.com.cn/s/blog_79c5bdc30100t88i.html 我自己实现的一种可以很方便的实现更换TabBarController图片的方法,代 ...