当前位置: 首页 > 工具软件 > ExcelUtil > 使用案例 >

ExcelUtil 工具类

孟祯
2023-12-01

maven 依赖

<!-- java poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>
<!--支持xlsx读取-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.17</version>
</dependency>

工具类

package com.kurumi.util;


import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.CollectionUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author chenlong
 * @create 2022-03-09 20:20
 *
 * excel 工具类
 */
public class ExcelUtil {

    /**
     * 将 list 导入 excel
     * @param list list 数据列表
     * @param obj list 的实体对象
     * @param fileName 文件名称
     * @param response response
     */
    public static void writeListToExcel(List<?> list, Class obj, String fileName, HttpServletResponse response) {
        ExcelUtil.writeListToExcel(list,obj,null,null,fileName,response);
    }

    /**
     * 将 list 导入 excel
     * @param list list 数据列表
     * @param obj list 的实体对象
     * @param rows 导出的列
     * @param fileName 文件名称
     * @param response response
     */
    public static void writeListToExcel(List<?> list, Class obj,String[] rows,String fileName, HttpServletResponse response) {
        ExcelUtil.writeListToExcel(list,obj,null,rows,fileName,response);
    }


    /**
     * 将 list 导入 excel
     * @param list list 数据列表
     * @param obj list 的实体对象
     * @param header 表头数组  (为 null 时,实体类中属性名作为表头)
     * @param rows 导出的列  (为 null 导出所有列)
     * @param fileName 文件名称
     * @param response response
     */
    public static void writeListToExcel(List<?> list, Class obj, String[] header, String[] rows,String fileName, HttpServletResponse response) {
        try {
            //1.创建工作簿
            Workbook book = new XSSFWorkbook();

            //2.创建 sheet 页
            Sheet sheet = book.createSheet();

            //获取 get 方法
            List<Method> methods = new LinkedList<>();
            if (rows == null || rows.length == 0) {
                //获取实体类中所有列 get 方法
                BeanInfo beanInfo = Introspector.getBeanInfo(obj);
                MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors();
                for (int i = 0; i < methodDescriptors.length; i++) {
                    String method = methodDescriptors[i].getName();
                    if (Pattern.matches("[g][e][t]\\w*",method) && !"getClass".equals(method)) {
                        methods.add(methodDescriptors[i].getMethod());
                    }
                }
            } else {
                //获取指定列的 get 方法
                for (int i = 0; i < rows.length; i++) {
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(rows[i], obj);
                    methods.add(propertyDescriptor.getReadMethod());
                }
            }
            if (header == null || header.length == 0) {
                header = new String[methods.size()];
                for (int i = 0; i < header.length; i++) {
                    String methodName = methods.get(i).getName();
                    header[i] = methodName.substring(3,4).toLowerCase() + methodName.substring(4);
                }
            }


            //3.创建表头
            Row headerRow = sheet.createRow(0);
            CellStyle headerStyle = getHeaderStyle(book);
            setHeaderRow(header, headerRow, headerStyle);

            //4.填充数据
            int sheetFlag = 0;
            if (!CollectionUtils.isEmpty(list)) {
                for (int i = 0; i < list.size(); i++) {
                    //超过最大行数,自动创建下一页
                    if ((i+1)%1048575 == 0) {
                        sheet = book.createSheet("sheet" + sheetFlag);
                        headerRow = sheet.createRow(0);
                        setHeaderRow(header, headerRow, headerStyle);
                        sheetFlag ++;
                    }
                    //getLastRowNum 获取行标(表头行标为 0)
                    Row row = sheet.createRow(sheet.getLastRowNum() + 1);
                    Object o = list.get(i);
                    for (int j = 0; j < methods.size(); j++) {
                        Object value = methods.get(j).invoke(o);
                        row.createCell(j).setCellValue(value != null ? value.toString() : "-");
                    }
                }
            }

            //5.将 excel 表格导出
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes(StandardCharsets.UTF_8),"ISO8859-1") + ".xlsx");
            ServletOutputStream outputStream = response.getOutputStream();
            book.write(outputStream);
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 设置表头
     * @param header
     * @param headerRow
     * @param headerStyle
     */
    private static void setHeaderRow(String[] header, Row headerRow, CellStyle headerStyle) {
        for (int i = 0; i < header.length; i++) {
            Cell headerCell = headerRow.createCell(i);
            headerCell.setCellValue(header[i]);
            headerCell.setCellStyle(headerStyle);
        }
    }

    /**
     * 表头样式
     * @param book
     */
    private static CellStyle getHeaderStyle(Workbook book) {
        CellStyle headerStyle = book.createCellStyle();
        Font headerFont = book.createFont();
        headerFont.setBold(true); //设置粗体
        headerFont.setFontName("表头加粗字体");
        headerStyle.setFont(headerFont);
        return headerStyle;
    }

}

 类似资料: