excel文件导入导出(java版)

1.导入数据

 //字节输入流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //通过输入流创建ExcelReader 对象
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //这个同上导入
//        reader.addHeaderAlias("序号","id");
        reader.addHeaderAlias("企业名称","companyName");
        reader.addHeaderAlias("承诺信息","commitmentInformation");
        reader.addHeaderAlias("风险等级","riskGrade");
        reader.addHeaderAlias("上报时间","reportTime");


        List companyAnnouncementDTOS = reader.readAll(CompanyAnnouncementDTO.class);
        for (CompanyAnnouncementDTO companyAnnouncementDTO : companyAnnouncementDTOS) {
            CompanyAnnouncement companyAnnouncement = new CompanyAnnouncement();
            BeanUtils.copyProperties(companyAnnouncementDTO,companyAnnouncement);
            companyAnnouncementMapper.insert(companyAnnouncement);
        }
    }

2.导出

@PostMapping(value = "export")
@ApiOperation("导出")
public void exportData(@RequestBody  List ids, HttpServletResponse response) throws IOException {
    List dtos = iCompanyAnnouncementService.exportData(ids);

    try {
        response.setContentType("application/ms-excel;charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("安全承诺公告", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), CompanyAnnouncementDTO.class).autoCloseStream(Boolean.FALSE).head(CompanyAnnouncementDTO.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("安全承诺公告")
                .doWrite(dtos);
    } catch (Exception e) {
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

    }
}

你可能感兴趣的:(java,excel,算法)