崛起於Springboot2.X + 200秒解決文件導入導出(56)

《SpringBoot2.X心法總綱》數據庫

使用ExcelUtil快速實現對文件的導入導出系列。瀏覽器

一、pom文件

<dependency>
    <groupId>net.oschina.likaixuan</groupId>
    <artifactId>excelutil</artifactId>
    <version>3.0.1</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

二、實體類

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    @Excel(title = "姓名")
    private String name;
    @Excel(title = "學號")
    private String stu_no;
    @Excel(title = "年齡")
    private int age;
}

三、controller接口

@RestController
public class ExcelController {

    /**
     * @Author:MuJiuTian
     * @Date:2019/11/9 下午3:14
     * @Description:excel導入數據
     */
    @PostMapping(value = "/importFile")
    public void importFile(MultipartFile file) throws Exception {
        // 一、讀取文件列表內容
        List<Student> students = ExcelUtil.readXls(file.getBytes(),Student.class);

        // 二、處理業務邏輯,最後存儲數據庫操做,此步驟忽略,只講ExcelUitl用法

        // 三、輸出,打印到控制檯
        students.stream().forEach(System.out::println);
    }

    /**
     * @Author:MuJiuTian
     * @Date:2019/11/9 下午3:14
     * @Description:數據導出到excel
     */
    @GetMapping(value = "/exportFile")
    public void exportFile(HttpServletResponse response) throws Exception {
        // 一、根據條件將須要導出數據查找出來 studentService.selectAll();這裏不作處理
        List<Student> students = Arrays.asList(
                new Student("小湯","2013245060501",20),
                new Student("王軒","2013245060502",21),
                new Student("紫玉","2013245060503",18)
        );

        // 二、導出到具體路徑(如d盤或者mac桌面)
        ExcelUtil.exportExcel("",students,Student.class);

        // 三、導出到瀏覽器(正常狀況下咱們使用瀏覽器下載)
        ExcelUtil.exportExcelOutputStream(response,students,Student.class);
    }


    // 測試 導入
    @PostMapping(value = "/test_import")
    public void test_import() throws Exception {
        List<Student> students = ExcelUtil.readXls("/Users/tentsuuhou/Desktop/excelutil.xlsx",Student.class);
        students.stream().forEach(System.out::println);
    }

    // 測試 導出
    @GetMapping(value = "/test_export")
    public void test_export(HttpServletResponse response) throws Exception {

        List<Student> students = Arrays.asList(
                new Student("小湯","2013245060501",20),
                new Student("王軒","2013245060502",21),
                new Student("紫玉","2013245060503",18)
        );
        ExcelUtil.exportExcelOutputStream(response,students,Student.class);
    }
}

四、測試導入

測試導入接口,準備文件如圖:app

執行接口:框架

http://localhost:8081/test_import

結果以下:測試

五、測試導出

執行接口:spa

http://localhost:8081/test_export

結果:.net

成功!3d

ExcelUtil框架Git地址excel

相關文章
相關標籤/搜索