zhanghua
2023-09-05 1c732150ad5e8b21efff07ecd923c4ff8fda60c1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.ycl.utils;
 
import com.alibaba.excel.EasyExcel;
import com.ycl.dto.UmsDepartDto;
import com.ycl.utils.listener.DepartListener;
import lombok.SneakyThrows;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
 
public class EasyExcelUtils {
 
    /**
     * @Description 导出
     * @Param [response , sheetName sheet名字, className 类名, collection data]
     * @return void
     **/
    @SneakyThrows
    public static void export(HttpServletResponse response, String sheetName, Class className, Collection<?> collection) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ".xlsx");
        EasyExcel.write(response.getOutputStream(), className)
                .sheet(sheetName)
                .doWrite(collection);
    }
 
    @SneakyThrows
    public static void export1(HttpServletResponse response, String sheetName, Class className, Collection<?> collection, String fileName) {
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + fileName  + ".xlsx");
        EasyExcel.write(response.getOutputStream(), className)
                .sheet(sheetName)
                .doWrite(collection);
    }
 
    @SneakyThrows
    public static void importDepartFile(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream())
                .head(UmsDepartDto.class)
                .registerReadListener(new DepartListener()).sheet().doRead();
    }
 
}