Springboot导出Excel并下载

引入相关依赖

<!--数据导出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","用户名","账号","密码","备注"};

        ExcelExport2.export(response,usersMapper.selectAll(),arr);

    }

}

工具类

文件导出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;
    }

}

类操作工具类

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");
    }
}

原文地址:https://www.cnblogs.com/Createsequence/p/11563460.html

时间: 2024-08-26 13:03:45

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

list数据导出excel并且下载到本地

最近做grid列表相关数据导出到excel功能,根据自己选择的列导出成excel 并且下载到本地.下载位置根据配置文件进行的配置.废话不说 直接上关键代码: 需要引入相关的包: compile 'net.sourceforge.jexcelapi:jxl:2.6.12'这是我项目中gradle的配置. @Override public void exportExcel(Integer[] ids,HttpServletResponse response) { List<WithdrawDepos

Java导出excel并下载功能

我们使用的导出并下载功能是利用一个插件叫POI的插件提供的导出功能,很实用:首先先导入Jar包: Jar包下载地址:http://poi.apache.org/   官方文档地址:http://poi.apache.org/spreadsheet/quick-guide.html Action代码: public void exportToExcel(List<PortalContactVO> data) throws Exception { this.setEnableAccessReque

MVC导出Excel,提供下载Excel

类1: using System.Collections.Generic;using System.Data;using System.Web.Mvc;using System.IO;using System.Web.UI.WebControls;using System.Web;using System.Web.UI;using System.Drawing; namespace Base.ActionResult{    public class ExcelResult : System.W

(十一)SpringBoot导出excel文件

一:添加POI依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> 二:创建Excel实体类 package com.example.demo.model; import java.io.Serializable; impo

DataTable数据导出Excel 并且下载

public string Excel(System.Data.DataTable dt) { //模板的路径 string strUploadPath = HttpContext.Current.Server.MapPath("../template/"); //模板的名称 string strFileName = strUploadPath + "JobTicketTemplate.xlsx"; FileInfo TemplateFile = new FileI

导出Excel并下载,但无法定制样式的方法!

拿来的,望原创见谅! public void EXCELDown(DataTable dt, string strFileName) { Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); Response.AppendHeader("Content-Disposition", "attachment;filename=" + strFileName + &

springboot 导出excel

依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>p

Springboot利用poi导出excel下载

Springboot利用poi导出excel下载 因为项目中之前的做法是用反射获取属性,所以demo中也是用的反射,我看网上很多文章都是存入一个List中,不知道这两种哪种更何合适一点,或者有什么更好的方法也请大佬们赐教. pom <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.13</version&g

poi 架包导出excel,并下载

导出excel在许多系统中都有应用到,这里以两个简单例子作为介绍: 1.导入poi-3.9.jar,可以在官网下载http://poi.apache.org . 2.先写一个简单的测试类,里面有详细的解释,代码如下: 1 import java.io.FileOutputStream; 2 import java.io.IOException; 3 import org.apache.poi.hssf.usermodel.HSSFCell; 4 import org.apache.poi.hss