使用EasyExcel导出导入excel文件

依赖

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

导出

创建实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class StudentInfoDTO implements Serializable {

    @ExcelProperty("ID")
    @ColumnWidth(10)
    private Long id;

    @ExcelProperty("姓名")
    @ColumnWidth(10)
    private String name;

    @ExcelProperty("性别")
    @ColumnWidth(10)
    private String sex;

    @ExcelProperty("年龄")
    @ColumnWidth(10)
    private Integer age;

    @ExcelProperty("备注")
    @ColumnWidth(10)
    private String beiZhu;
}

Controller层(Service,dao层省略)

/**
     * 导出
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/exportStudentInfoList")
    public void exportStudentInfoList(HttpServletResponse response) throws Exception {
        setExcelRespProp(response, "学生信息列表");
        List<StudentInfoDTO> studentInfoList = studentInfoService.getStudentInfoList();
        ExcelUtil.writeExcel(response, studentInfoList, "学生信息列表", "学生信息列表", StudentInfoDTO.class);
    }

ExcelUtil


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

public class ExcelUtil {
    /**
     * 导出 Excel :一个 sheet,带表头.
     *
     * @param response  HttpServletResponse
     * @param  data      数据 list,每个元素为一个 BaseRowModel
     * @param fileName  导出的文件名
     * @param sheetName 导入文件的 sheet 名
     * @param model     映射实体类,Excel 模型
     * @throws Exception 异常
     */

    public static void writeExcel(HttpServletResponse response, List<? extends Object> data, String fileName, String sheetName, Class model) throws Exception {
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        //设置表头居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 颜色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        // 字体
        headWriteCellStyle.setWriteFont(headWriteFont);
        headWriteCellStyle.setWrapped(true);
        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        //设置内容靠中对齐
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        EasyExcel.write(getOutputStream(fileName, response), model).excelType(ExcelTypeEnum.XLSX).sheet(sheetName).registerWriteHandler(horizontalCellStyleStrategy)
                //最大长度自适应 目前没有对应算法优化 建议注释掉不用 会出bug
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(data);

    }

    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("导出excel表格失败!", e);
        }
    }

}

导入

controller层

/**
     * 导入
     * @param file
     * @throws IOException
     */
    @RequestMapping(value = "/importStudentInfoList")
    public void importStudentInfoList(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(),StudentInfoDTO.class,new ExcelListener()).sheet().doReadSync();
    }

创建监听器实现导入逻辑


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.syb.springboottestdemo.dto.StudentInfoDTO;

import java.util.Map;

public class ExcelListener extends AnalysisEventListener<StudentInfoDTO> {
    @Override
    public void invoke(StudentInfoDTO studentInfoDTO, AnalysisContext analysisContext) {
        //每读一行的回调处理
        ReadRowHolder readRowHolder = analysisContext.readRowHolder();
        Integer rowIndex = readRowHolder.getRowIndex();
        System.out.println("第"+rowIndex+"行数据"+studentInfoDTO);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //所有数据读取完毕后回调处理
        System.out.println("解析导入完成");
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        //对表头的处理
        System.out.println("表头:-----"+headMap);
    }
}

文件保存方法

public void saveFileToLocal(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            InputStream input = file.getInputStream();
            OutputStream outputStream = new FileOutputStream("D:/" + File.separator + fileName);
            byte[] b = new byte[4096];
            int count = input.read(b);
            while (count != -1) {
                for (int i = 0; i < count; i++) {
                    outputStream.write(b[i]);
                }
                count = input.read(b);
            }
            input.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
posted @ 2022-07-25 17:01  Cv工程师120621号  阅读(238)  评论(0)    收藏  举报