EasyExecl匯出模板,實現動態下拉列
阿新 • • 發佈:2021-01-27
1.需要效果.
2.pom.xml 依賴jar包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.0.2</version>
</dependency>
3.自定義註解
/** * 自定義註解標記匯出excel的下拉資料集 * Author xianyu * Date 2021-01-20 */ @Documented // 作用在欄位上 @Target(ElementType.FIELD) // 執行時有效 @Retention(RetentionPolicy.RUNTIME) public @interface DropDownSetField { // 固定下拉內容 String[] source() default {}; String name() default ""; }
4.實體類新增 easyexecl註釋 和自定義註釋
@Data public class ProductModel extends BaseRowModel { @ApiModelProperty(value = "商品名稱" ,example = "商品名稱") @ExcelProperty(value = "商品名稱", index = 0) private String productName; @ApiModelProperty(value = "商品分類id" ,example = "1") @ExcelProperty(value = "商品分類", index = 1) @DropDownSetField(name = "productCategoryName") private String productCategoryName; @ApiModelProperty(value = "銷售方式" ,example = "1") @ExcelProperty(value = "銷售方式", index = 2) @DropDownSetField(name = "salesMode") private String salesMode; @ApiModelProperty(value = "是否時價 0->否 1->是" ,example = "1") @ExcelProperty(value = "是否時價", index = 3) @DropDownSetField(source = {"否","是"}) private String curpriceStatus; @ApiModelProperty(value = "商品規格" ,example = "規格") @ExcelProperty(value = "商品規格", index = 4) @DropDownSetField(name = "format") private String format; @ApiModelProperty(value = "條碼" ,example = "條碼") @ExcelProperty(value = "條碼", index = 5) private String barCode; @ApiModelProperty(value = "零售價" ,example = "6.66") @ExcelProperty(value = "零售價", index = 6) private BigDecimal retailPrice; @ApiModelProperty(value = "進價" ,example = "6.66") @ExcelProperty(value = "進價", index = 7) private BigDecimal purchasPrice; @ApiModelProperty(value = "會員價" ,example = "6.66") @ExcelProperty(value = "會員價", index = 8) private BigDecimal memberPrice; @ApiModelProperty(value = "配送價" ,example = "6.66") @ExcelProperty(value = "配送價", index = 9) private BigDecimal dispatchPrice; @ApiModelProperty(value = "批發價" ,example = "6.66") @ExcelProperty(value = "批發價", index = 10) private BigDecimal tradePrice; @ApiModelProperty(value = "初始庫存" ,example = "1") @ExcelProperty(value = "初始庫存", index = 11) private BigDecimal stock; @ApiModelProperty(value = "供應商" ,example = "1") @ExcelProperty(value = "供應商", index = 12) @DropDownSetField(name = "supplier") private String supplier; @ApiModelProperty(value = "商品單位" ,example = "1") @ExcelProperty(value = "商品單位", index = 13) @DropDownSetField(name = "productUnit") private String productUnit; @ApiModelProperty(value = "商品品牌" ,example = "1") @ExcelProperty(value = "商品品牌", index = 14) @DropDownSetField(name = "productBrand") private String productBrand; @ApiModelProperty(value = "進貨規格" ,example = "進貨規格") @ExcelProperty(value = "進貨規格", index = 15) private String purchaseSpec; @ApiModelProperty(value = "產地" ,example = "產地") @ExcelProperty(value = "產地", index = 16) private String placeOrigin; @ApiModelProperty(value = "上架狀態:0->下架;1->上架" ,example = "1") @ExcelProperty(value = "上下架", index = 17) @DropDownSetField(source = {"下架","上架"}) private String publishStatus; }
5.邏輯處理
@SneakyThrows @Override public void exportExcel(HttpServletResponse response) { try { // 獲取該類宣告的所有欄位 Field[] fields = ProductModel.class.getDeclaredFields(); // 響應欄位對應的下拉集合 Map<Integer, String[]> map = new HashMap<>(); Field field = null; // 迴圈判斷哪些欄位有下拉資料集,並獲取 for (int i = 0; i < fields.length; i++) { field = fields[i]; // 解析註解資訊 DropDownSetField dropDownSetField = field.getAnnotation(DropDownSetField.class); if (null != dropDownSetField) { String name = dropDownSetField.name(); if (!StringUtils.isEmpty(name)) { if (name.equals(Constants.productCategoryName)) { //當前欄為 分類 欄,處理 分類 下拉框 List<String> list = productCategoryMapper.selectCategoryNameAll(); if(CollectionUtils.isEmpty(list)){ continue; } String[] params = list.toArray(new String[list.size()]); insertMap(map, params, dropDownSetField, i); } if (name.equals(Constants.salesMode)) { //當前欄為 銷售方式 欄,處理 銷售方式 下拉框 List<String> list = sysDictDataMapper.selectDictLabelAllByDictType(Constants.pms_sales_mode); if(CollectionUtils.isEmpty(list)){ continue; } String[] params = list.toArray(new String[list.size()]); insertMap(map, params, dropDownSetField, i); } if (name.equals(Constants.supplier)) { //當前欄為 銷售方式 欄,處理 銷售方式 下拉框 List<String> list = sysDictDataMapper.selectDictLabelAllByDictType(Constants.pms_supplier); if(CollectionUtils.isEmpty(list)){ continue; } String[] params = list.toArray(new String[list.size()]); insertMap(map, params, dropDownSetField, i); } if (name.equals(Constants.productUnit)) { //當前欄為 商品單位 欄,處理 商品單位 下拉框 List<String> list = sysDictDataMapper.selectDictLabelAllByDictType(Constants.pms_product_unit); if(CollectionUtils.isEmpty(list)){ continue; } String[] params = list.toArray(new String[list.size()]); insertMap(map, params, dropDownSetField, i); } if (name.equals(Constants.productBrand)) { //當前欄為 商品品牌 欄,處理 商品品牌 下拉框 List<String> list = sysDictDataMapper.selectDictLabelAllByDictType(Constants.pms_product_brand); if(CollectionUtils.isEmpty(list)){ continue; } String[] params = list.toArray(new String[list.size()]); insertMap(map, params, dropDownSetField, i); } if (name.equals(Constants.format)) { //當前欄為 商品規格 欄,處理 商品規格 下拉框 List<String> list = productSpecMapper.findSpecNameAll(); if(CollectionUtils.isEmpty(list)){ continue; } String[] params = list.toArray(new String[list.size()]); insertMap(map, params, dropDownSetField, i); } }else { insertMap(map,null,dropDownSetField,i); } } } //檔案以流形式返回前端下載 String fileName="spmb.xlsx"; OutputStream fileOutputStream = null; response.setHeader("Content-Disposition", "attachment;filename=" + fileName); response.setContentType("application/x-download"); response.setCharacterEncoding("UTF-8"); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); response.flushBuffer(); fileOutputStream = response.getOutputStream(); ExcelWriter excelWriter = EasyExcel.write(fileOutputStream, ProductModel.class) .registerWriteHandler(new ProductCellWriteHandler(map)).build(); WriteSheet sheet = EasyExcel.writerSheet(0, "商品模板").build(); excelWriter.write(null, sheet); excelWriter.finish(); fileOutputStream.flush(); fileOutputStream.close(); }catch (Exception e){ e.printStackTrace(); throw new GlobalException("下載模板失敗!"); }
6.工具類
public class ResoveDropAnnotationUtil {
private static String productCategoryName = "productCategoryName"; //商品分類名
private static String salesMode = "salesMode"; //銷售方式
private static String pms_sales_mode = "pms_sales_mode"; //銷售方式字典key
private static String format = "format"; //規格
private static String supplier = "supplier"; //供應商
private static String pms_supplier = "pms_supplier"; //供應商字典key
private static String productUnit = "productUnit"; //商品單位
private static String pms_product_unit = "pms_product_unit"; //商品單位字典key
private static String productBrand = "productBrand"; //商品品牌
private static String pms_product_brand = "pms_product_brand"; //商品品牌字典key
public static String[] resove(DropDownSetField dropDownSetField, String[] strings) {
if (!Optional.ofNullable(dropDownSetField).isPresent()) {
return null;
}
// 獲取固定下拉資訊
String[] source = dropDownSetField.source();
if (null != source && source.length > 0) {
return source;
}
if (null != strings && strings.length > 0) {
try {
String[] dynamicSource = strings;
if (null != dynamicSource && dynamicSource.length > 0) {
return dynamicSource;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
//插入到map中
private void insertMap(Map<Integer, String[]> map, String[] params, DropDownSetField dropDownSetField, int i) {
String[] sources = ResoveDropAnnotationUtil.resove(dropDownSetField, params);
if (null != sources && sources.length > 0) {
map.put(i, sources);
}
}
@SneakyThrows
public static void main(String[] args) {
File file = new File("D:/商品匯入模板.xlsx");
// 檔案不存在即建立 存在即返回false
file.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(file);
// 獲取該類宣告的所有欄位
Field[] fields = ProductModel.class.getDeclaredFields();
// 響應欄位對應的下拉集合
Map<Integer, String[]> map = new HashMap<>();
Field field = null;
// 迴圈判斷哪些欄位有下拉資料集,並獲取
int num = 0;
for (int i = 0; i < fields.length; i++) {
System.out.println(i);
field = fields[i];
// 解析註解資訊
DropDownSetField dropDownSetField = field.getAnnotation(DropDownSetField.class);
if (null != dropDownSetField) {
String name = dropDownSetField.name();
if (!StringUtils.isEmpty(name)) {
// if (name.equals(productCategoryName)) {
// List<String> productCategoryList = productCategoryMapper.selectCategoryNameAll();
// }
}
List<String[]> strings = new ArrayList<>();
strings.add(new String[]{"g", "kg", "磅", "t", "ml", "l", "米", "千米"});
strings.add(new String[]{"1", "2", "3", "4", "5", "6", "7", "8"});
//String[] sources = ResoveDropAnnotationUtil.resove(dropDownSetField, strings);
// if (null != sources && sources.length > 0) {
//
// map.put(i, sources);
//
// }
}
}
ExcelWriter excelWriter = EasyExcel.write(fileOutputStream, ProductModel.class)
.registerWriteHandler(new ProductCellWriteHandler(map)).build();
WriteSheet sheet = EasyExcel.writerSheet(0, "商品模板").build();
excelWriter.write(null, sheet);
excelWriter.finish();
}
}