欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot导出excel表格(easyExcel)

程序员文章站 2022-03-15 10:16:21
...

官方文档
https://www.yuque.com/easyexcel/doc/quickstart

  1. 导入pom依赖
<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.1.6</version>
</dependency>

2.实体类

@ExcelProperty是设置excel中的第一行


@Data
@AllArgsConstructor
@NoArgsConstructor
public class Form {
    @ExcelProperty("id")
    private int id;
    @ExcelProperty("老师id")
    private int teacherId;
    @ExcelProperty("课程id")
    private int lessonId;
    @ExcelProperty("学生表现")
    private String studentScore;
    @ExcelProperty("老师表现")
    private String teacherScore;
    @ExcelProperty("建议")
    private String suggestion;
    @ExcelProperty("等级")
    private int rank;

    @ExcelProperty("课程名")
    private String lessonName;
    @ExcelProperty("任课老师名字")
    private String teacherName;

    private String img;

}

  1. 为了方便,我就直接写在controller类中了
    肯定有更好的实现方式
 @GetMapping("/print")
 @ResponseBody
    public String simpleWrite(HttpServletResponse response) throws IOException {
    	//文件名
        String name=System.currentTimeMillis()+".xlsx";
        //PATH是存储路径
        String fileName = PATH+name;
		//得到查询结果forms,这不是重点
        List<Form> forms = adminService.selectAll();
        for (Form form : forms) {
            form.setTeacherName(teacherService.selectById(form.getTeacherId()).getName());
            form.setLessonName(lessonService.selectById(form.getLessonId()).getName());
            System.out.println(form);
        }
        //这一步是保存到本地,
        EasyExcel.write(fileName, Form.class).sheet("课程评价").doWrite(forms);

        //从本地下载文件
        download(fileName,response,name);
        return "success";

    }
    //下载excel文件
    public void download(String fileName,HttpServletResponse res,String name) {
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + name);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File( fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("download success");
    }

右下角浏览器就会自动下载了
springboot导出excel表格(easyExcel)

相关标签: springboot java