一、引入相关依赖

<!--数据导出excel-->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>

二、Controller接口

package com.huang.controller;

import com.huang.mapper.UsersMapper;
import com.huang.util.excelExport.ExcelExport2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; /**
* @Author:huang
* @Date:2019-09-21 13:13
* @Description:<描述>
*/
@Controller
public class TestController { @Resource
private UsersMapper usersMapper; @RequestMapping("/test")
public void testExprotExcel(HttpServletResponse response){ //创建一个数组用于设置表头
String[] arr = new String[]{"ID","用户名","账号","密码","备注"}; //调用Excel导出工具类
ExcelExport2.export(response,usersMapper.selectAll(),arr); } }

三、工具类

3.1文件导出excel工具类

大体思路是传入一个需要导出的数据集合,获取该对象类,然后遍历集合,使用下面的类操作工具类,通过反射获取对象类的属性的get方法,然后将数据对象的值取出来放到excel里

package com.huang.util.excelExport;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row; import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List; /**
* @Author:haung
* @Date:2019-09-21 11:21
* @Description:Excel导出工具类,依赖于ClassUtil工具类
*/
public final class ExcelExport2 { /**
* 将传入的数据导出excel表并下载
* @param response 返回的HttpServletResponse
* @param importlist 要导出的对象的集合
* @param attributeNames 含有每个对象属性在excel表中对应的标题字符串的数组(请按对象中属性排序调整字符串在数组中的位置)
*/
public static void export(HttpServletResponse response, List<?> importlist, String[] attributeNames) {
//获取数据集
List<?> datalist = importlist; //声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
//生成一个表格
HSSFSheet sheet = workbook.createSheet();
//设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 18); //获取字段名数组
String[] tableAttributeName = attributeNames;
//获取对象属性
Field[] fields = ClassUtil.getClassAttribute(importlist.get(0));
//获取对象get方法
List<Method> methodList = ClassUtil.getMethodGet(importlist.get(0)); //循环字段名数组,创建标题行
Row row = sheet.createRow(0);
for (int j = 0; j< tableAttributeName.length; j++){
//创建列
Cell cell = row.createCell(j);
//设置单元类型为String
cell.setCellType(CellType.STRING);
cell.setCellValue(transCellType(tableAttributeName[j]));
}
//创建普通行
for (int i = 0;i<datalist.size();i++){
//因为第一行已经用于创建标题行,故从第二行开始创建
row = sheet.createRow(i+1);
//如果是第一行就让其为标题行
Object targetObj = datalist.get(i);
for (int j = 0;j<fields.length;j++){
//创建列
Cell cell = row.createCell(j);
cell.setCellType(CellType.STRING);
//
try {
Object value = methodList.get(j).invoke(targetObj, new Object[]{});
cell.setCellValue(transCellType(value));
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
response.setContentType("application/octet-stream");
//默认Excel名称
response.setHeader("Content-Disposition", "attachment;fileName="+"test.xls"); try {
response.flushBuffer();
workbook.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
} } private static String transCellType(Object value){
String str = null;
if (value instanceof Date){
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
str = sdf.format(date);
}else{
str = String.valueOf(value);
if (str == "null"){
str = "";
}
} return str;
} }

3.2类操作工具类

该工具类用于Excel导出工具类里的属性操作

package com.huang.util.excelExport;

import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List; /**
* @Author:huang
* @Date:2019-09-21 13:41
* @Description:关于类的操作的工具类
*/
public final class ClassUtil { private ClassUtil() {
throw new Error("工具类不允许实例化!");
} /**
* 获取类属性
* @param targetObj 要获取属性的类
* @return 含有类属性的集合
*/
public static Field[] getClassAttribute(Object targetObj){ Class<?> objectClass = targetObj.getClass();
return objectClass.getDeclaredFields(); } /**
* 获取对象的所有get或set方法
* @param targetObj 要获取属性的类
* @param methodKeyword get或者set关键字
* @return 含有类get或set方法的集合
*/
public static List<Method> getMethod(Object targetObj,String methodKeyword){
List<Method> methodList = new ArrayList<>(); Class<?> objectClass = targetObj.getClass(); Field[] field = objectClass.getDeclaredFields();
for (int i = 0;i<field.length;i++){
//获取属性名并组装方法名
String fieldName = field[i].getName();
String getMethodName = methodKeyword
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1); try {
Method method = objectClass.getMethod(getMethodName,new Class[]{});
methodList.add(method);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
return methodList;
} /**
* 获取对象的所有get方法
* @param targetObj 要获取属性的类
* @return 含有类方法的集合
*/
public static List<Method> getMethodGet(Object targetObj){
return getMethod(targetObj,"get");
} /**
* 获取对象的所有set方法
* @param targetObj 要获取属性的类
* @return 含有类方法的集合
*/
public static List<Method> getMethodSet(Object targetObj){
return getMethod(targetObj,"set");
}
}

四、后续补充的话

说实在的,我自己都没想到随便写的东西能有这么高的点击数,这篇文章是做项目的时候第一次遇到导出Excel需求的时候写的,当时头铁硬生生自己造了个轮子出来,上述代码可以用,但是仍然存在表头设置麻烦,内存占用高,而且导出数据可控性低的问题。实际上,针对这个需求,如果是需要导出大量数据而没有排版要求的话,可以用EasyExcel,顺带还能把Excel导入给解决了;如果是需要按照复杂模板导出的话,可以使用jxls,或者大佬进一步封装的jxlss。这些都是实用而且成熟的轮子,无意耽误了各位时间,属实抱歉......

Springboot导出Excel并下载的更多相关文章

  1. JS导出excel设置下载的标题/与angular结合冲突

    2017.8更新 此功能与angular结合使用时,最后一行 document.getElementById("dlink").click(); 与angular的ng-click ...

  2. SpringBoot导出excel数据报错Could not find acceptable representation

    转自:https://blog.csdn.net/mate_ge/article/details/93518286?utm_source=distribute.pc_relevant.none-tas ...

  3. POI导出Excel并下载

    首先在pom.xml添加jar包: <!-- 导出excel --> <dependency> <groupId>org.apache.poi</groupI ...

  4. POI导出excel并下载(以流的形式在客户端下载,不保存文件在服务器上)

    import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; i ...

  5. Java导出excel并下载功能

    我们使用的导出并下载功能是利用一个插件叫POI的插件提供的导出功能,很实用:首先先导入Jar包: Jar包下载地址:http://poi.apache.org/   官方文档地址:http://poi ...

  6. django 导出excel react下载 --- 导出并下载

    Dajngo查询数据,查询出来之后生成Excel保存本地 class ExportExcel(APIView): def post(self, request, *args, **kwargs): e ...

  7. MVC导出Excel,提供下载Excel

    类1: using System.Collections.Generic;using System.Data;using System.Web.Mvc;using System.IO;using Sy ...

  8. Java poi 导出Excel并下载到客户端

    Maven配置,包含了其他文件格式的依赖,就全贴出来了 <dependency> <groupId>org.apache.poi</groupId> <art ...

  9. (十一)SpringBoot导出excel文件

    一:添加POI依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-oox ...

随机推荐

  1. jupyter login

    anaconda2/lib/python2.7/site-packages/notebook/auth/login.py """Tornado handlers for ...

  2. mybatis 语句中where 后边要跟必要条件和多个选择条件处理方法

    <select id="serchRelation" resultType="Relation">SELECTr.node_one as nodeO ...

  3. js获取整个屏幕的尺寸

    原文 首先获取屏幕宽度:window.screen.width;    //整个屏幕的宽度. 然后获取屏幕高度:window.screen.height;     //整个屏幕的高度. 获取可用工作区 ...

  4. leetcode探索高级算法

    C++版 数组和字符串 正文 链表: 正文 树与图: 树: leetcode236. 二叉树的最近公共祖先 递归(先序) leetcode124二叉树最大路径和 递归 图: leetcode 547朋 ...

  5. leetcode30 串联所有单词的子串

    先对words中的单词排列组合,然后对s滑窗操作:部分样例超时,代码如下: class Solution { public: vector<int> findSubstring(strin ...

  6. Java端使用Batik将SVG转为PNG

    在上篇中,我们需要将Highcharts生成的图通过后台保存到pdf文件中,就需要对SVG进行转换. 这里就介绍一下使用Batik处理SVG代码的方法. 首先是jar包的获取地址,https://xm ...

  7. 问题root@localhost's password:localhost:permission denied,please try again

    转载:https://www.cnblogs.com/hmy-blog/p/6500909.html 经过试验,上述方法在我的电脑中没有成功. 1.安装 open ssh:sudo apt-get i ...

  8. python用cx_Oracle连接oracle

    确认版本: oracle版本:64位 python版本:64位 下载cx_Oracle的whl包:64位 安装whl包:pip install wheel cd到下载路径安装cx_Oracle的whl ...

  9. [GPU] Machine Learning on C++

    一.MPI为何物? 初步了解:MPI集群环境搭建 二.重新认识Spark 链接:https://www.zhihu.com/question/48743915/answer/115738668 马铁大 ...

  10. openstack核心组件--neutron网络服务(4)

    一.neutron 介绍:   Neutron 概述 传统的网络管理方式很大程度上依赖于管理员手工配置和维护各种网络硬件设备:而云环境下的网络已经变得非常复杂,特别是在多租户场景里,用户随时都可能需要 ...