easypoi導出帶動態下拉框

easypoi導出帶動態下拉框。

實體註解:

package com.springbooteasypoi.entity.excel.select;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;

/**
 * Created by Administrator on 2022/12/6.
 */
@Data
public class Student {
    @Excel(name = "姓名",width = 20)
    private String name;
    
    // 動態下拉框字段:dict,addressList = true
    @Excel(name = "學生類型",dict = "level",addressList = true,width = 20)
    private String type;
}

handler:

package com.springbooteasypoi.handler.excel.select;

import cn.afterturn.easypoi.handler.inter.IExcelDictHandler;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2022/12/6.
 */
@Component
public class ExcelDicHandler implements IExcelDictHandler {
    @Override
    public List<Map> getList(String dict) {
        List<Map>           list    = new ArrayList<>();
        Map<String, String> dictMap = new HashMap<>();
        dictMap.put("dictKey", "0");
        dictMap.put("dictValue", "嚴重瞌睡");
        list.add(dictMap);
        dictMap = new HashMap<>();
        dictMap.put("dictKey", "1");
        dictMap.put("dictValue", "小B");
        list.add(dictMap);
        dictMap = new HashMap<>();
        dictMap.put("dictKey", "2");
        dictMap.put("dictValue", "深度富有");
        list.add(dictMap);
        return list;
    }

    // 導出用到
    @Override
    public String toName(String dict, Object obj, String name, Object value) {
        if ("level".equals(dict)) {
            int level = Integer.parseInt(value.toString());
            switch (level) {
                case 1:
                    return "小B";
                case 0:
                    return "嚴重瞌睡";
                case 2:
                    return "深度富有";
            }
        }
        return null;
    }

    // 導入用到
    @Override
    public String toValue(String dict, Object obj, String name, Object value) {
        if ("level".equals(dict)) {
            String valueStr = String.valueOf(value);
            switch (valueStr) {
                case "小B":
                    return "1";
                case "嚴重瞌睡":
                    return "0";
                case "深度富有":
                    return "2";
            }
        }
        return null;
    }
}

導入導出:

package com.springbooteasypoi.controller.excel.select;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.springbooteasypoi.entity.excel.select.Student;
import com.springbooteasypoi.entity.response.ResponseObjectResult;
import com.springbooteasypoi.entity.response.ResponseStatus;
import com.springbooteasypoi.entity.response.ResultCode;
import com.springbooteasypoi.handler.excel.select.ExcelDicHandler;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @description: 動態下拉框
* @author liuyachao
* @date 2022/12/6 12:34
*/
@RestController
@RequestMapping("/select")
public class SelectController {
    // 無數據導出
    @PostMapping("/exportDynamicSelect")
    public void exportTest(HttpServletResponse resp){
        try {
            ExportParams exportParams = new ExportParams("測試", "測試");
            exportParams.setDictHandler(new ExcelDicHandler());
            exportParams.setCreateHeadRows(true);
            List<Student> list = new ArrayList<>();
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Student.class, list);
            File filePath = new File("D:/easypoi");
            if(!filePath.exists()){
                filePath.mkdirs();
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            File localFile = new File("D:/easypoi" + File.separator + "test" + sdf.format(new Date()) + ".xls");
            localFile.setReadable(true, false);
            OutputStream os = new FileOutputStream(localFile);
            workbook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // 有數據導出
    @PostMapping("/exportDynamicSelect2")
    public void exportTest2(HttpServletResponse resp){
        try {
            ExportParams exportParams = new ExportParams("測試", "測試");
            exportParams.setDictHandler(new ExcelDicHandler());
            exportParams.setCreateHeadRows(true);
            List<Student> list = new ArrayList<>();
            Student s1 = new Student();
            s1.setName("xiao");
            s1.setType("0");
            Student s2 = new Student();
            s2.setName("da");
            s2.setType("1");
            list.add(s1);
            list.add(s2);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Student.class, list);
            File filePath = new File("D:/easypoi");
            if(!filePath.exists()){
                filePath.mkdirs();
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            File localFile = new File("D:/easypoi" + File.separator + "test" + sdf.format(new Date()) + ".xls");
            localFile.setReadable(true, false);
            OutputStream os = new FileOutputStream(localFile);
            workbook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    // 導入
    @PostMapping("/importDynamicSelect")
    public ResponseObjectResult importDynamicSelect(@RequestPart(value = "file") MultipartFile file,
                                    HttpServletResponse resp){
        try {
            //判斷文件是否存在
            if (file == null) {
                return new ResponseObjectResult(new ResponseStatus(ResultCode.ILLEGALINPUT));
            }
            //獲得文件名
            String fileName = file.getOriginalFilename();

            //判斷文件是否是excel文件
            if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
                return new ResponseObjectResult(new ResponseStatus(10001, "不是excel文件", false));
            }

            ImportParams params = new ImportParams();
            //設置標題佔行
            params.setTitleRows(1);
            //設置表頭佔行
            params.setHeadRows(1);
            //解決空行問題 選擇一個不爲空的列
            params.setKeyIndex(1);
            //sheet位置 從0開始
//        params.setStartSheetIndex(0);
//        params.setStartRows(2);
            //代表導入這裏是需要驗證的(根據字段上的註解校驗)
            params.setNeedVerify(true);
            params.setDictHandler(new ExcelDicHandler());

            //獲取excel文件的io流
            List<Student> list = null;
            try {
                InputStream is = file.getInputStream();
                ExcelImportResult<Student> result = ExcelImportUtil.importExcelMore(is, Student.class, params);
                list = result.getList();
                //失敗結果集
                List<Student> failList = result.getFailList();
                //拿到導出失敗的工作簿
                Workbook failWorkbook = result.getFailWorkbook();
//            Workbook workbook = result.getWorkbook();
                //驗證是否有失敗的數據
                if (result.isVerifyFail()) {
                    ServletOutputStream fos = resp.getOutputStream();
                    //mime類型
                    resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                    resp.setHeader("Content-disposition", "attachment;filename=error.xlsx");
                    result.getFailWorkbook().write(fos);
//                workbook.write(fos);
//                failWorkbook.write(fos);
                    fos.close();
                    // java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
                    //return new ResponseObjectResult(new ResponseStatus(ResultCode.FAIL),failList);
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new ResponseObjectResult(new ResponseStatus(ResultCode.SUCCESS));
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseObjectResult(new ResponseStatus(ResultCode.FAIL));
        }
    }
}

效果圖:

導出空數據模板:

 

 導出:

 

 導入:

 

 注意:

如果註解沒有addressList,需升級easypoi版本,我的是由4.1.3升級到了4.3.0就有了。

<!--使用easypoi,可以導出大數量的文件-->
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.3.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>4.3.0</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>4.3.0</version> <!--4.1.3-->
        </dependency>

 easpoi的api文檔:

http://doc.wupaas.com/docs/easypoi/easypoi-1c2cp5rf3hnqv

老版本:

http://easypoi.mydoc.io/#text_202975

新版本纔有下拉框相關api。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章