easypoi 实现兼容2003和2007excel 下拉选项

easypoi导出添加下拉选项

<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>3.3.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-web</artifactId>
    <version>3.3.0</version>
</dependency>
<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-annotation</artifactId>
    <version>3.3.0</version>
</dependency>


@GetMapping("/export")
    public void exportExcel(HttpServletResponse response){
        List<Person> list=new ArrayList<>();
        Person p1=new Person("1");
        Person p2=new Person("2");

        list.add(p1);
        list.add(p2);

        //参数配置
        ExportParams params = new ExportParams();
        //此处设置ExcelType HSSF为excel2003版本,XSSF为excel2007版本
       // params.setType(ExcelType.HSSF);
        params.setType(ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Person.class, list);
       // ExcelPoiUtil.createHssfSelected(workbook, 0, 0, new String[]{"男","女"});
        ExcelPoiUtil.createXssfSelected(workbook, new String[]{"男","女"},0);
        ExcelPoiUtil.downloadExcel(response, workbook, "test");

    }





@PostMapping("/import")
    public void importExcel2(@RequestParam("file") MultipartFile file) {
        ImportParams importParams = new ImportParams();
        // 数据处理
        //importParams.setHeadRows(0);
        importParams.setTitleRows(0);
        // 需要验证
        importParams.setNeedVerfiy(true);
        try {
            ExcelImportResult<Person> result = ExcelImportUtil.importExcelMore(file.getInputStream(), Person.class,
                    importParams);
            List<Person> successList = result.getList();
            for (Person demoExcel : successList) {
                System.out.println(demoExcel);
            }
        } catch (IOException e) {
           log.error("IOException e={}",e);
        } catch (Exception e) {
            log.error("Exception e={}",e);
        }
    }





package com.cmbchina.ccd.oa.hrtransfer.model.bo;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
 * @description: ***
 * @author: sy0025
 * @create: 2019-10-29
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {

    @Excel(name = "性别", replace = { "未知_0", "男_1", "女_2" })
    private String sex;

}






package com.cmbchina.ccd.oa.hrtransfer.util;

import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @description: ***
 * @author: sy0025
 * @create: 2019-10-30
 */
public class ExcelPoiUtil {
    /**
     * 下载通用配置
     *
     * @param response  HttpServletResponse
     * @param workbook  Workbook
     * @param excelName excelName
     */
    public static void downloadExcel(HttpServletResponse response, Workbook workbook, String excelName) {
        try (OutputStream os = response.getOutputStream()) {

            response.reset();
            if (excelName == null) {
                excelName = UUID.randomUUID().toString();
            }
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "inline; filename=" + new String(excelName.getBytes("gb18030"), "ISO8859-1") + ".xlsx");
            workbook.write(os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** HSSF
     * firstRow 開始行號 根据此项目,默认为1(下标0开始)
     * lastRow  根据此项目,默认为最大65535
     * firstCol 区域中第一个单元格的列号 (下标0开始)
     * lastCol 区域中最后一个单元格的列号
     * strings 下拉内容
     * */
    public static void createHssfSelected(Workbook workbook,int firstCol,int lastCol,String[] strings ){

        Sheet sheet = workbook.getSheetAt(0);
        //  生成下拉列表
        //  只对(x,x)单元格有效
        CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(1, 65535, firstCol, lastCol);
        //  生成下拉框内容
        DVConstraint dvConstraint = DVConstraint.createExplicitListConstraint(strings);
        HSSFDataValidation dataValidation = new HSSFDataValidation(cellRangeAddressList, dvConstraint);

        //  对sheet页生效
        sheet.addValidationData(dataValidation);

    }

    /**XSSF
     * excel添加下拉数据校验
     * @param workbook 哪个 sheet 页添加校验
     * @param dataSource 数据源数组
     * @param col 第几列校验(0开始)
     * @return
     */
    public static void createXssfSelected(Workbook workbook, String[] dataSource, int col) {
        Sheet sheet = workbook.getSheetAt(0);
        CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(1, 65535, col, col);

        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = helper.createExplicitListConstraint(dataSource);

        DataValidation dataValidation = helper.createValidation(constraint, cellRangeAddressList);


        //处理Excel兼容性问题
        if (dataValidation instanceof XSSFDataValidation) {
            dataValidation.setSuppressDropDownArrow(true);
            dataValidation.setShowErrorBox(true);
        } else {
            dataValidation.setSuppressDropDownArrow(false);
        }

        dataValidation.setEmptyCellAllowed(true);
        dataValidation.setShowPromptBox(true);
        dataValidation.createPromptBox("提示", "只能选择下拉框里面的数据");
        sheet.addValidationData(dataValidation);;
    }

}

你可能感兴趣的:(技术)