springboot整合导入导入

目录

引入依赖

 导入接口

 服务层

 模型层

工具类 


 

引入依赖


    com.alibaba
    easyexcel
    2.2.6

 导入接口

 @PostMapping("batchAddCardData")
    @ApiOperation("批量添加名片数据")
    public ResponseVO batchAddCardData(@RequestParam("file")  MultipartFile file) {
        try {
            boolean flag = cardInfoService.batchAddCardData(file);
            if (!flag){throw new Exception();}
            return ResponseVO.getSuccessResponseVo(null, "批量添加成功");
        } catch (Exception e) {
            throw new BusinessException("批量添加失败,注意选择excel文档");
        }
    }

 服务层

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchAddCardData(MultipartFile file) {
        try {
            // 获取目标文件夹位置
            File folder = new File("src/main/java/com/pi/namecardadmin/excel");
            if (!folder.exists()){
                folder.mkdirs();
            }
            File dest = new File(folder.getAbsolutePath());
            // 将文件写入到目标文件夹
            file.transferTo(dest);
            List cardInfos = ExcelUtil.getDataFromExcel(CardInfo.class, dest.getPath());
            cardInfos.stream()
                            .parallel()
                            .peek(cardInfo -> {
                                cardInfo.setCardId(generateShortId());
                                cardInfoMapper.insert(cardInfo);
                            })
                            .count();
            // 删除该临时文件
            dest.delete();
            return true;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     采用UUID获取唯一的CardId
     */
    public static String generateShortId() {
        UUID uuid = UUID.randomUUID();
        long mostSigBits = uuid.getMostSignificantBits();
        long leastSigBits = uuid.getLeastSignificantBits();
 
        // 将 UUID 的最高位和最低位转换成 16 进制字符串
        String mostSigHex = Long.toHexString(mostSigBits);
        String leastSigHex = Long.toHexString(leastSigBits);
 
        // 拼接最高位和最低位,并截取前11位作为最终的短 ID
        String shortId = mostSigHex + leastSigHex;
        return shortId.substring(0, 11);
    }

 模型层

@TableName("card_info")
@Data
@AllArgsConstructor
@NoArgsConstructor
@HeadStyle(horizontalAlignment = HorizontalAlignment.CENTER,verticalAlignment = VerticalAlignment.CENTER, shrinkToFit = true)//标题样式,垂直水平居中
@HeadFontStyle(fontName = "微软雅黑",fontHeightInPoints = 11,bold = false)//表头字体样式
@HeadRowHeight(value = 35)//表头行高
@ContentFontStyle(fontName = "微软雅黑",fontHeightInPoints = 11)//内容字体样式
@ContentRowHeight(value = 30)//内容行高
@ContentStyle(horizontalAlignment = HorizontalAlignment.CENTER,verticalAlignment = VerticalAlignment.CENTER, wrapped = true)//内容样式,垂直水平居中
public class CardInfo implements Serializable {
 
    private static final long serialVersionUID = 1L;
 
    @TableId(value = "id", type = IdType.AUTO)
    @ExcelIgnore
    private Long id;
 
    /**
     * 卡片id
     */
    @ExcelProperty("cardId")
    private String cardId;
 
    /**
     * 真实姓名
     */
    @ExcelProperty("name")
    private String name;
 
    /**
     * 年龄
     */
    @ExcelProperty("age")
    private Integer age;
 
    /**
     * 职业
     */
    @ExcelProperty("occupation")
 
    private String occupation;
 
    /**
     * 电话号码
     */
    @ExcelProperty("phone")
    private String phone;
 
    /**
     * 地址
     */
    @ExcelProperty("address")
    private String address;
 
    /**
     * 邮箱
     */
    @ExcelProperty("email")
    private String email;
 
    /**
     * 公司
     */
    @ExcelProperty("company")
    private String company;
 
    /**
     * 0:未删除1:逻辑删除2:真正删除
     */
    @ExcelIgnore
    private Integer delFlag;
 
    /**
     * 用户id(不是必要)
     */
    @ExcelProperty("userId")
    private String userId;
 
    /**
     * 名片曝光率
     */
    /**不显示字段注解*/
    @ExcelIgnore
    private Long exposureValue;
 
    /**
     * 标签集合
     */
    @TableField(value="tag_list",typeHandler = FastjsonTypeHandler.class)
    @ExcelProperty("tagList")
    private String tagList;
 
    /**
     * 名片用户的简介
     */
    @ExcelProperty("personalProfile")
    private String personalProfile;
 
}

工具类 

 

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.poi.ss.formula.functions.T;
import java.util.LinkedList;
import java.util.List;
 
/**
 * @author wzx
 */
public class ExcelUtil {
 
 
    /**
     * 封装Excel中的数据到指定的实体类中
     * @param typeClass 指定的实体类的字节码类别
     * @param readPath Excel的文件路径
     * @return 指定的实体类对象的集合(每个对象代表每一条数据)
     */
    public static List getDataFromExcel(Class typeClass , String readPath){
        List list = new LinkedList<>();
        EasyExcel.read(readPath)
                .head(typeClass)
                .sheet()
                .registerReadListener(new AnalysisEventListener() {
 
                    @Override
                    public void invoke(T excelData, AnalysisContext analysisContext) {
                        list.add(excelData);
                    }
 
                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        System.out.println("数据读取完毕");
                    }
                }).doRead();
        return list;
    }
 
    /**
     * 将封装好的数据写入Excel中
     * @param list 写入的数据集合
     * @param writePath 写入的Excel文件的路径
     * @param sheet excel表中生成的sheet表名
     * @param excelType 插入的excel的类别,有xls、xlsx两种
     */
    public static  void saveDataToExcel(List list, String writePath, String sheet, ExcelTypeEnum excelType, Class clazz) {
        // 写入Excel文件
        EasyExcel.write(writePath)
                .head(clazz)
                .excelType(excelType)
                .sheet(sheet)
                .doWrite(list);
    }
}

你可能感兴趣的:(spring,boot,后端,java)