项目学习《第九天》ExcelUtil 将数据导出excel表

本文记录了解决mapper配置文件读取问题后,使用ExcelUtil工具类实现数据导出Excel的功能。通过深入理解并应用Field类,实现根据字段名获取值,并提供了设置自动列宽、填充数据等方法。提供了四种不同参数的listToExcel方法,支持导出到本地或浏览器,以及自定义工作表大小。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天早上,终于解决了无法读取mapper配置文件的问题!!!!!!!
修改了yml配置文件中mapper-locations
以前是这么写的
mapper-locations: classpath/mapper/*.xml
以下是修改后的

mybatis:
  config-location: classpath:/mybatis-config.xml
  mapper-locations: classpath:templates/mapper/*.xml
  type-aliases-package: com.sjx.model

也就是说在路径前面添加了templates,我想说不是默认读取的就是临时文件下的吗?不配置就读取不到,必须要加上才可以读取到,记住了记住了长记性了太折磨人了!

导出excel

下面要实现一个功能,就是将数据导出excel表。
首先需要一个exceUtil工具类来导出Excel(可以导出到本地文件系统,也可以导出到浏览器,可自定义工作表大小)

ExcelUtil

原作者写的这个工具类方法够多够复杂,边写边解析。

首先就是定义了一个ExcelException内部自定义异常类

    class ExcelException  extends Exception{

        public ExcelException() {
            // TODO Auto-generated constructor stub
        }

        public ExcelException(String message) {
            super(message);
            // TODO Auto-generated constructor stub
        }

        public ExcelException(Throwable cause) {
            super(cause);
            // TODO Auto-generated constructor stub
        }

        public ExcelException(String message, Throwable cause) {
            super(message, cause);
            // TODO Auto-generated constructor stub
        }
}

Field getFieldByName方法:根据字段名获取字段

    /*根据字段名获取字段 (字段名,包含该字段的类)*/
    private static Field getFieldByName(String fieldName, Class<?> clazz){
        /*拿到本类的所有字段*/
        Field[] selfFields = clazz.getDeclaredFields();

        /*如果本类中存在该字段,则返回*/
        for (Field field : selfFields) {
            if (field.getName().equals(fieldName)){
                return field;
            }

        }

        /*否则,查看父类中是否存在此字段,如果有则返回*/
        Class<?> superClazz = clazz.getSuperclass();
        if (superClazz != null && superClazz != Object.class){
            return getFieldByName(fieldName, superClazz);
        }

        /*如果本类和父类都没有,则返回空*/
        return null;
    }

拓展Filed类
Java中Field 提供有关类或接口的单个字段的信息,以及对它的动态访问权限。反射的字段可能是一个类字段或实例字段。Field是成员变量的意思。Field也是一个类,该类位于java.lang.reflect包下。
Field提供如下几种方法:
1、Class.getDeclaredField(String name);
返回一个 Field 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明字段(包括私有成员)。
2、Class.getDeclaredFields();
返回 Field 对象的一个数组,该数组包含此 Class 对象所表示的类或接口所声明的所有字段(包括私有成员)。
3、Class.getField(String name);
返回一个 Field 对象,它反映此 Class 对象所表示的类或接口的指定公共成员字段。
4、Class.getFields();
返回一个包含某些 Field 对象的数组,该数组包含此 Class 对象所表示的类或接口的所有可访问公共字段。

Object getFieldValueByName方法:根据字段名获取字段值

    /*根据字段名获取字段值 (字段名, 对象)*/
    private static Object getFieldValueByName(String fieldName, Object o) throws Exception{

        Object value = null;
        Field field = getFieldByName(fieldName,o.getClass());

        if (field != null){
            field.setAccessible(true);
            value = field.get(o);
        }else {
            return new ExcelException(o.getClass().getSimpleName() + "类不存在字段名" + fieldName);
        }

        return value;

    }

Object getFieldValueByNameSequence方法:根据带路径或不带路径的属性名获取属性值

  /*根据带路径或不带路径的属性名获取属性值(带路径的属性名或简单属性名,对象)
    既接受简单属性名,如userName等,又接受带路径的属性名,如student.department.name等*/
    private static Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception{

        Object value = null;

        //将fieldNameSequence进行拆分
        String[] attributes = fieldNameSequence.split("\\.");
        if (attributes.length == 1){
            value = getFieldValueByName(fieldNameSequence,o);
        }else {
            //根据属性名获取属性对象
            Object fieldObj = getFieldValueByName(attributes[0], o);
            String subFieldNameSequence = fieldNameSequence.substring(fieldNameSequence.indexOf(".") + 1);
            value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj);

        }

        return value;

    }

void setColumnAutoSize方法:设置工作表自动列宽和首行加粗

    /*设置工作表自动列宽和首行加粗*/
    private static void setColumnAutoSize(WritableSheet ws , int extraWith){
        //获取本列的最宽单元格的宽度
        for (int i = 0; i < ws.getColumns(); i++) {
            int colWith = 0;
            for (int j = 0; j < ws.getRows(); j++) {
                String content = ws.getCell(i, j).getContents().toString();
                int cellWith = content.length();
                if (colWith < cellWith){
                    colWith = cellWith;
                }
            }

            //设置单元格的宽度为最宽宽度+额外宽度
            ws.setColumnView(i, colWith + extraWith);
        }
    }

void fillSheet方法:向工作表中填充数据

    /*向工作表中填充数据*/
    private static <T> void fillSheet(
            WritableSheet sheet, //工作表
            List<T> list, //数据源
            LinkedHashMap<String, String> fieldMap, //中英字段对应关系的Map
            int firstIndex, //开始索引
            int lastIndex //结束索引
    ) throws Exception{

        //定义存放英文字段名和中文字段名的数组
        String[] enFields = new String[fieldMap.size()];
        String[] cnFields = new String[fieldMap.size()];

        //填充数组
        int count = 0;
        for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
            enFields[count] = entry.getKey();
            cnFields[count] = entry.getValue();
            count++;
        }

        //填充表头
        for (int i = 0; i < cnFields.length; i++) {
            Label label = new Label(i, 0, cnFields[i]);
            sheet.addCell(label);
        }

        //填充内容
        int rowNo = 1;
        for (int index = firstIndex; index <= lastIndex; index++){
            //获取单个对象
            T item = list.get(index);
            for (int i = 0; i < enFields.length; i++) {
                Object objValue = getFieldValueByNameSequence(enFields[i],item);
                String fieldValue = objValue == null ? "" : objValue.toString();
                Label label = new Label(i, rowNo, fieldValue);
                sheet.addCell(label);
            }

            rowNo++;
        }

        /*设置自动列宽*/
        setColumnAutoSize(sheet, 5);
        
    }

四个重载的listToExcel方法

1.导出Excel(可以导出到本地文件系统,也可以导出到浏览器,可自定义工作表大小)

/*导出Excel(可以导出到本地文件系统,也可以导出到浏览器,可自定义工作表大小)*/
    public static <T> void listToExcel(
            List<T> list, //数据源
            LinkedHashMap<String, String> fieldMap, //类的英文属性和Excel中的中文列名的对应关系
            String sheetName, //工作表的名称
            int sheetSize, //每个工作表中记录的最大个数
            OutputStream out //导出流
    ) throws ExcelException {

        if (list.size() == 0 || list == null) {
            throw new ExcelException("数据源中没有任何数据");
        }

        if (sheetSize > 65535 || sheetSize < 1) {
            sheetSize = 65535;
        }

        //创建工作薄并发送到OutputStream指定的地方中
        WritableWorkbook wwb = null;

        try {

            wwb = Workbook.createWorkbook(out);

            //因为2003的Excel一个工作表最多可以有65536条记录,除去列头剩下65535条
            //所以如果记录太多,需要放到多个工作表中,其实就是个分页的过程
            //1.计算一共有多少个工作表
            double sheetNum = Math.ceil(list.size() / new Integer(sheetSize).doubleValue());
            //2.创建相应的工作表,并向其中填充数据
            for (int i = 0; i < sheetNum; i++) {
                //如果只有一个工作表的情况下
                if (1 == sheetNum) {
                    WritableSheet sheet = wwb.createSheet(sheetName, i);
                    fillSheet(sheet, list, fieldMap, 0, list.size() - 1);

                    //有多个工作表的情况
                } else {
                    WritableSheet sheet = wwb.createSheet(sheetName + (i + 1), 1);

                    //获取开始索引和结束索引
                    int firstIndex = i * sheetSize;
                    int lastIndex = (i + 1) * sheetSize - 1 > list.size() - 1 ? list.size() - 1 : (i + 1) * sheetSize - 1;
                    //填充工作表
                    fillSheet(sheet, list, fieldMap, firstIndex, lastIndex);
                }

            }
            wwb.write();
            wwb.close();

        } catch (Exception e) {
            e.printStackTrace();
            //如果是ExcelException,则直接抛出
            if (e instanceof ExcelException) {
                throw (ExcelException) e;

                //否则将其他异常包装成ExcelException
            } else {
                throw new ExcelException("导出Excel失败");
            }

        }
    }

2.可以导出到本地文件系统,也可以导出到浏览器,工作表大小为2003支持的最大值

    /*导出Excel(可以导出到本地文件系统,也可以导出到浏览器,工作表大小为2003支持的最大值)*/
    public static <T> void listToExcel(
            List<T> list, //数据源
            LinkedHashMap<String, String> fieldMap, //类的英文属性和Excel中的中文列名的对应关系
            String sheetName, //工作表的名称
            OutputStream out //导出流
    ) throws ExcelException {

        listToExcel(list, fieldMap, sheetName, 65535, out);

    }

3.导出Excel(导出到浏览器,可以自定义工作表的大小)

/*导出Excel(导出到浏览器,可以自定义工作表的大小)*/
    public static <T> void listToExcel(
            List<T> list, //数据源
            LinkedHashMap<String, String> fieldMap, //类的英文属性和Excel中的中文列名的对应关系
            String sheetName, //工作表的名称
            int sheetSize, //每个工作表中记录的最大个数
            HttpServletResponse response //使用response可以导出到浏览器
    ) throws ExcelException {

        //设置默认文件名为当前时间:年月日时分秒
        String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();

        //设置response头信息
        response.reset();  //清空buffer,设置页面不缓存
        response.setContentType("application/vnd.ms-excel"); //改成输出excel文件
        response.setHeader("Content-disposition","attachment; filename=" + fileName + ".xls");

        //创建工作薄并发送到浏览器
        try {

            ServletOutputStream out = response.getOutputStream();
            listToExcel(list, fieldMap, sheetName, sheetSize, out);

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

            //如果是ExcelException,则直接抛出
            if (e instanceof ExcelException) {
                throw (ExcelException) e;

                //否则将其他异常包装成ExcelException再抛出
            }else {
                throw new ExcelException("导出Excel失败");
            }
        }

    }

4.导出Excel(导出到浏览器,工作表的大小是2003支持的最大值)

    /*导出Excel(导出到浏览器,工作表的大小是2003支持的最大值)*/
    public static <T> void listToExcel(
            List<T> list, //数据源
            LinkedHashMap<String, String> fieldMap, //类的英文属性和Excel中的中文列名的对应关系
            String sheetName, //工作表的名称
            HttpServletResponse response //使用response可以导出到浏览器
    )throws ExcelException{

        listToExcel(list, fieldMap, sheetName, 65535, response);

    }

今天就先到这里了 ps:解决了三天没有解决的bug心情还是很棒的!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值