Java uses easyexcel to export excel (customizable export fields)

Java uses easyexcel to export excel (customizable export fields)
The following instructions are for the needs of custom export field data. If you don’t need custom export fields, you can ignore the tool class for exporting excel. You only need the first method in the tool class at the end. Just export it.

First import the coordinates

		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.0.5</version>
        </dependency>

The custom export field is passed in from the front end, and the field and field name need to be passed in. If you do not need to customize the export field, you can omit this step and directly add the corresponding field export annotation to the returned entity, and then write in the collector
insert image description here
layer

@PostMapping("/download")
    @ApiOperation(value = "导出")
    public void exportColumn(HttpServletRequest request,HttpServletResponse response,@RequestBody DzrStockDTO stockDTO){
    
    
        request.getSession();
        dzrStockService.exportColumn(response,stockDTO);
    }

Business layer writing

@Override
    public void exportColumn(HttpServletResponse response, DzrStockDTO stockDTO) {
    
    
        Assert.isTrue(CollectionUtils.isNotEmpty(stockDTO.getHeadList()) && CollectionUtils.isNotEmpty(stockDTO.getColumnList()),"导出字段和名称不能为空!");
        stockDTO.setPageNum(1);
        stockDTO.setPageSize(60000);
        //导出的数据
        List<Object> list = (List<Object>) getList(stockDTO).getRows();
        String name = "导出excel名称";
        LeadingOutUtil.upload(response,stockDTO.getHeadList(),stockDTO.getColumnList(),list,name);
    }

Since there are multiple exports, the export method is extracted as a public tool. The details are as follows, which can be used directly, and the parameters can be modified by yourself.

package com.sydata.fmimp.entity.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author xx
 * @Date 2023/3/14 14:23
 * @Description: 选字段导出工具类
 * @Version 1.0
 */
@Slf4j
public class LeadingOutUtil {
    
    

    /**
     * 选择字段导出数据
     * @param response
     * @param headList 文件导出字段名称
     * @param columnList 文件导出字段
     * @param list 导出数据
     * @param name 文件名
     */
    public static void upload(HttpServletResponse response,List<String> headList,List<String> columnList, List<Object> list, String name) {
    
    
        try {
    
    
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode(name, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream())
                    .head(head(headList))
                    //自适应列宽
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .includeColumnFiledNames(columnList)
                    .sheet(name)
                    .doWrite(dataList(list,columnList));
        } catch (IOException e) {
    
    
            e.printStackTrace();
            log.error(e.getMessage(),e);
        }
    }

    /**
     * 设置Excel头
     * @param headList  Excel头信息
     * @return
     */
    public static List<List<String>> head(List<String> headList) {
    
    
        List<List<String>> list = new ArrayList<>();
        for (String value : headList) {
    
    
            List<String> head = new ArrayList<>();
            head.add(value);
            list.add(head);
        }
        return list;
    }

    /**
     * 设置表格信息
     * @param dataList  查询出的数据
     * @param fileList  需要显示的字段
     * @return
     */
    public static List<List<Object>> dataList(List<Object> dataList, List<String> fileList) {
    
    
        List<List<Object>> list = new ArrayList<>();
        for (Object object : dataList) {
    
    
            List<Object> data = new ArrayList<>();
            for (String fieldName : fileList) {
    
    
                //通过反射根据需要显示的字段,获取对应的属性值
                data.add(getFieldValue(fieldName, object));
            }
            list.add(data);
        }
        return list;
    }

    /**
     * 根据传入的字段获取对应的get方法,如name,对应的getName方法
     * @param fieldName  字段名
     * @param object    对象
     * @return
     */
    private static Object getFieldValue(String fieldName, Object object) {
    
    
        try {
    
    
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = object.getClass().getMethod(getter);
            return method.invoke(object);
        } catch (Exception e) {
    
    
            return null;
        }
    }
}

illustrate

EasyExcel.write(response.getOutputStream())
                    .head(head(headList))
                    //自适应列宽
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .includeColumnFiledNames(columnList)
                    .sheet(name)
                    .doWrite(dataList(list,columnList));

headList: It is the header field of excel. If you do not need to customize the export field, you can directly access the annotation of the export field in the entity class, and then replace the entity class. Annotation class name: The name of the exported sheet page list:
Need
insert image description here
to
export data

Guess you like

Origin blog.csdn.net/weixin_51114236/article/details/129536213