Hutool 导出Excel,只导出设置了别名的字段

只导设置别名的字段

Hutool 的导出会默认将实体类(或Map)的所有字段都导出来,有时候根据业务的需求不要一些多余的字段,这就很烦,请教了一下大佬,知道有这么一个方法

bigWriter.setOnlyAlias(true); // 官方提供了这个方法,参数为true时只导出有别名的

工具类

public class HuExcelUtils {

    /**
     * excel 导出工具类
     *
     * @param response
     * @param fileName    文件名
     * @param collection  对象集合
     * @param columnNames 字段名
     * @param alias       字段对应的别名
     * @param columnWidth 列宽(可以为null) -  默认宽度25
     */
    public static void exportExcel(HttpServletResponse response, String fileName, Collection<?> collection, 
            String[] columnNames, String[] alias, int[] columnWidth) {
        ExcelWriter bigWriter = ExcelUtil.getBigWriter();
        if (columnWidth == null || columnNames.length != columnWidth.length) {
            // 设置默认宽度 
            for (int i = 0; i < columnNames.length; i++) {
                bigWriter.addHeaderAlias(columnNames[i], alias[i]);
                bigWriter.setColumnWidth(i, 25);
            }
        } else {
            // 设置自定义宽度 
            for (int i = 0; i < columnNames.length; i++) {
                bigWriter.addHeaderAlias(columnNames[i], alias[i]);
                bigWriter.setColumnWidth(i, columnWidth[i]);
            }
        }
        
        // 设置只导出有别名的字段
        bigWriter.setOnlyAlias(true);
        // 设置默认行高
        bigWriter.setDefaultRowHeight(18);
        // 设置冻结行
        bigWriter.setFreezePane(1);
        // 一次性写出内容,使用默认样式,强制输出标题
        bigWriter.write(collection, true);
        
        ServletOutputStream out = null;
        
        try {
            //response为HttpServletResponse对象
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            // 文件名支持中文
            response.setHeader("Content-Disposition", 
                    "attachment;filename=" + 
                    URLEncoder.encode(fileName + DateUtil.today() + ".xlsx", "UTF-8"));
            out = response.getOutputStream();
            bigWriter.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭writer,释放内存
            bigWriter.close();
        }
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }

	/**
     * excel 导出工具类,字段和别名可以不用分开
     *
     * @param response
     * @param fileName    文件名
     * @param collection  对象集合
     * @param fieldAndAlias 字段和别名,Map<字段, 别名>  如:Map<"name", "姓名">
     * @param columnWidth 列宽(可以为null) -  默认宽度25
     */
    public static void exportExcel(HttpServletResponse response, String fileName, Collection<?> collection, 
            Map<String, String> fieldAndAlias, int[] columnWidth) {
        ExcelWriter bigWriter = ExcelUtil.getBigWriter();
        if (columnWidth == null || columnWidth.length != fieldAndAlias.size()) {
            // 设置默认宽度 
            for (int i = 0; i < fieldAndAlias.size(); i++) {
                bigWriter.setColumnWidth(i, 25);
            }
        } else {
            // 设置自定义宽度 
            for (int i = 0; i < columnWidth.length; i++) {
                bigWriter.setColumnWidth(i, columnWidth[i]);
            }
        }
        // 设置字段和别名
        bigWriter.setHeaderAlias(fieldAndAlias);
        // 设置只导出有别名的字段
        bigWriter.setOnlyAlias(true);
        // 设置默认行高
        bigWriter.setDefaultRowHeight(18);
        // 设置冻结行
        bigWriter.setFreezePane(1);
        // 一次性写出内容,使用默认样式,强制输出标题
        bigWriter.write(collection, true);
        
        ServletOutputStream out = null;
        
        try {
            //response为HttpServletResponse对象
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", 
                    "attachment;filename=" + 
                            URLEncoder.encode(fileName + DateUtil.today() + ".xlsx", "UTF-8"));
            out = response.getOutputStream();
            bigWriter.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭writer,释放内存
            bigWriter.close();
        }
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }
    
}

使用

@Controller
public class ReportController {
    
    @ResponseBody
    @RequestMapping("/export")
    public void export(HttpServletResponse response, ModelMap model, PdaDTO pdaDTO) {
        List<Map<String, Object>> data = pdaReportService.findScanCodeWarehousePageData(pdaDTO, null);

        // <字段名,标题>
        Map<String, String> fieldAndAlias = new LinkedHashMap<String, String>();
        fieldAndAlias.put("customer_code", "客户编码");
        fieldAndAlias.put("name", "客户名称");
        fieldAndAlias.put("product_code", "产品编码");
        fieldAndAlias.put("product_name", "产品名称");
        fieldAndAlias.put("product_spec", "规格");
        fieldAndAlias.put("product_category", "产品品类");
        fieldAndAlias.put("created_at", "扫码入库日期");
        fieldAndAlias.put("product_lot", "生产批次号");
        fieldAndAlias.put("code_type", "条码类型");
        fieldAndAlias.put("product_mdf", "生产日期");
        fieldAndAlias.put("effective_days", "效期");
        fieldAndAlias.put("memo", "备注");

        // 设置标题别名
        String[] alias = fieldAndAlias.values().toArray(new String[0]);
        // 设置单元格值
        String[] properties = fieldAndAlias.keySet().toArray(new String[0]);

        String fileName = "明细导出";
        HuExcelUtils.exportExcel(response, fileName, data, properties, alias, null);
    }
}
  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用 hutool 的 `ExcelWriter` 工具类结合反射机制实现只导出设置别名字段。具体步骤如下: 1. 定义一个实体类,使用 `@ExcelAlias` 注解为需要导出字段设置别名,例如: ```java public class User { @ExcelAlias("姓名") private String name; @ExcelAlias("年龄") private Integer age; // 省略 getter 和 setter 方法 } ``` 2. 在程序中创建 `ExcelWriter` 对象,并设置表头别名。例如: ```java ExcelWriter writer = ExcelUtil.getWriter(); writer.addHeaderAlias("姓名", "name"); writer.addHeaderAlias("年龄", "age"); ``` 3. 获取需要导出的数据列表,并使用反射机制获取需要导出字段值。例如: ```java List<User> userList = getUserList(); for (User user : userList) { List<Object> row = new ArrayList<>(); Field[] fields = user.getClass().getDeclaredFields(); for (Field field : fields) { ExcelAlias alias = field.getAnnotation(ExcelAlias.class); if (alias != null) { try { field.setAccessible(true); Object value = field.get(user); row.add(value); } catch (IllegalAccessException e) { e.printStackTrace(); } } } writer.writeRow(row); } ``` 完整示例代码如下: ```java import cn.hutool.core.util.ReflectUtil; import cn.hutool.poi.excel.ExcelUtil; import cn.hutool.poi.excel.ExcelWriter; import cn.hutool.poi.excel.annotation.ExcelAlias; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { ExcelWriter writer = ExcelUtil.getWriter(); writer.addHeaderAlias("姓名", "name"); writer.addHeaderAlias("年龄", "age"); List<User> userList = getUserList(); for (User user : userList) { List<Object> row = new ArrayList<>(); Field[] fields = user.getClass().getDeclaredFields(); for (Field field : fields) { ExcelAlias alias = field.getAnnotation(ExcelAlias.class); if (alias != null) { Object value = ReflectUtil.getFieldValue(user, field); row.add(value); } } writer.writeRow(row); } writer.flush(); writer.close(); } private static List<User> getUserList() { List<User> userList = new ArrayList<>(); userList.add(new User("张三", 18)); userList.add(new User("李四", 20)); userList.add(new User("王五", 22)); return userList; } @SuppressWarnings("unused") private static class User { @ExcelAlias("姓名") private String name; @ExcelAlias("年龄") private Integer age; public User(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } } } ``` 注意事项: 1. 需要使用 `@SuppressWarnings("unused")` 注解将 `User` 类标记为不使用,否则编译器会提示 `The type Test.User is never used locally` 的警告信息; 2. 需要使用 `field.setAccessible(true)` 将字段的访问权限设置为可访问,否则会抛出 `java.lang.IllegalAccessException: class Test cannot access a member of class xxx with modifiers "private"` 的异常信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值