Springboot2整合easypoi实现导入导出、OSS图片导出到Excel

提示这篇文件OSS图片导出到Excel表格是根据,上一篇文章来实现的。 如果不需要导出图片,请忽略关于OSS部分的内容以及工具类。

上一篇文章连接:https://blog.csdn.net/qq_41085151/article/details/107354263

1.添加pom依赖

       

       
            mysql
            mysql-connector-java
            runtime
        
        
            org.projectlombok
            lombok
            true
        
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.1.0
        
        
        
            com.alibaba
            druid
            1.1.6
        


        
            cn.afterturn
            easypoi-base
            3.2.0
        
        
            cn.afterturn
            easypoi-web
            3.2.0
        
        
            cn.afterturn
            easypoi-annotation
            3.2.0
        

      
            io.springfox
            springfox-swagger2
            2.7.0
        
        
        
            io.springfox
            springfox-swagger-ui
            2.7.0
        

2.配置文件

server.port=8083
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

mybatis-plus.configuration.map-underscore-to-camel-case=false

mybatis-plus.global-config.db-config.id-type=auto

mybatis-plus.global-config.db-config.db-type=mysql

spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=1000MB


#地域节点
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
#用户accesskey id
aliyun.oss.file.keyid=xxxxxxxxxx
#用户accesskey secret
aliyun.oss.file.keysecret=xxxxxxxxxx
#相当于是哪个库
aliyun.oss.file.bucketname=xiaozhuya
#文件路径
aliyun.oss.file.filehost=avatar

3.编写mybatis配置类和Swagger配置类

@Data
@Configuration
public class MybatisPlusConfig {

    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }
    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    @Bean
    public RestTemplate getRestTemplate(){
        return  new RestTemplate();
    }

    //逻辑删除
    @Bean
    public ISqlInjector sqlInjector() {
        return new LogicSqlInjector();
    }

}
@Configuration
@EnableSwagger2
public class Swagger2Config {

	@Bean
	public Docket webApiConfig(){

		return new Docket(DocumentationType.SWAGGER_2)
				.groupName("webApi")
				.apiInfo(webApiInfo())
				.select()
				//.paths(Predicates.not(PathSelectors.regex("/admin/.*")))
				.paths(Predicates.not(PathSelectors.regex("/error.*")))
				.build();

	}
	private ApiInfo webApiInfo(){
		return new ApiInfoBuilder()
				.title("网站-用户中心API文档")
				.description("本文档描述了课程中心微服务接口定义")
				.version("1.0")
				.contact(new Contact("Helen", "http://itlinli.com", "[email protected]"))
				.build();
	}

}

4.创建表编写pojo

CREATE TABLE `t_userinfo` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(20) DEFAULT NULL,
  `age` INT(3) DEFAULT NULL,
  `birthday` DATE DEFAULT NULL,
  `headimageurl` TEXT,
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8
@Data  //没有lombok写get和set方法
@TableName("t_userinfo")
public class User implements Serializable {
    // 主键id
    @ExcelIgnore // 生成报表时忽略,不生成次字段
    @TableId(type = IdType.AUTO)
    private Integer id;

    @NotEmpty(message = "不能为空")
    @Size(min = 2,max = 20,message = "长度不能超过2-20")
    @Excel(name = "姓名") // 定义表头名称和位置,0代表第一列
    private String name;

    @Size(max = 3,message = "年龄不能大于3位数")
    @Excel(name = "年龄")
    private Integer age;// 定义列宽

    @Excel(name = "生日", format = "yyyy-MM-dd", width = 15)
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    @Excel(name = "头像", type = 2 ,width = 20 , height = 40)//type = 2 :代表这个一个图片展示
    private  String   headImageurl;

}

5.编写Dao

@Mapper
public interface UserDao extends BaseMapper {
}

6.编写Service,如果不需要图片,忽略下载OSS图片

public interface UserService extends IService {
       void logDownload(Integer id, HttpServletResponse response) throws Exception;

       R download();//根据数据库url,下载oss图片保存到本地

       void exportExcelUser(HttpServletResponse response);

       List getUser();

       R importExcelUser(MultipartFile file);


}

7.easypoi工具类

public final class EasyPoiUtils {

    private EasyPoiUtils() {}

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new  RuntimeException(e);
        }
    }

    private static void defaultExport(List dataList, Class clz, String fileName, HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, clz, dataList);
        if (workbook != null) {
            downLoadExcel(fileName, response, workbook);
        }
    }

    public static void exportExcel(List dataList, String title, String sheetName, Class clz, String fileName, boolean isCreateHeader, HttpServletResponse response) {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(dataList, clz, fileName, response, exportParams);
    }

    public static void exportExcel(List dataList, String title, String sheetName, Class clz, String fileName, HttpServletResponse response) {
        defaultExport(dataList, clz, fileName, response, new ExportParams(title, sheetName));
    }

    private static void defaultExport(List> dataList, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(dataList, ExcelType.HSSF);
        if (workbook != null) {
            downLoadExcel(fileName, response, workbook);
        }
    }

    public static void exportExcel(List> dataList, String fileName, HttpServletResponse response) {
        defaultExport(dataList, fileName, response);
    }

    public static  List importExcel(String filePath, Integer titleRows, Integer headerRows, Class clz) {
        if (StringUtils.isBlank(filePath)) {
            return null;
        }

        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);

        try {
            return ExcelImportUtil.importExcel(new File(filePath), clz, params);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public static  List importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class clz) {
        if (file == null) {
            return null;
        }

        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);

        try {
            return ExcelImportUtil.importExcel(file.getInputStream(), clz, params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static List importExcel(MultipartFile file, Class clz) {
        if (file == null) {
            return null;
        }

        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        params.setHeadRows(1);
        try {
            return ExcelImportUtil.importExcel(file.getInputStream(), clz, params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private List downloadPicture(String fileName,List urlList) {
        File file=new File(fileName);
        // 不存在则创建文件夹
        if (!file.exists()){
            file.mkdir();
        }
        long imageNumber = System.currentTimeMillis();
        ListimageList=new ArrayList<>();
        URL url = null;
        for (String urlString : urlList) {
            try {
                url = new URL(urlString);
                DataInputStream dataInputStream = new DataInputStream(url.openStream());
                Random random=new Random();
                int rd=random.nextInt(9999);
                String imageName = imageNumber+""+rd + ".jpg";
                FileOutputStream fileOutputStream = new FileOutputStream(new File(fileName+"/"+imageName));
                byte[] buffer = new byte[1024];
                int length;
                while ((length = dataInputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, length);
                }
                dataInputStream.close();
                fileOutputStream.close();
                imageList.add(fileName+"/"+imageName);
                imageNumber++;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return imageList;
    }

}

8.编写实现类

@Service
@Slf4j
public class UserServiceImpl  extends ServiceImpl implements UserService {


    @Autowired
    UserDao userDao;
    @Override
    public void logDownload(Integer id, HttpServletResponse response) throws Exception {
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String fileHost = ConstantPropertiesUtil.FILE_HOST;
        User user = userDao.selectById(id);
        String imageurl = user.getHeadImageurl();
        String name = OSSStringUtil.urltoname(imageurl);


        //设置响应头为下载
        response.setContentType("application/force-download");
        //设置下载的文件名
        response.addHeader("Content-Disposition", "attachment;fileName=" + name);
        response.setCharacterEncoding("UTF-8");

        OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        String filePath = OSSStringUtil.urltofilepath(imageurl, fileHost);
        String osskey = OSSStringUtil.osskey(fileHost, filePath, name);
        OSSObject ossObject = ossClient.getObject(bucketName,osskey);
        InputStream is = ossObject.getObjectContent();
        BufferedInputStream bis = null;//定义缓冲流
        OSSStringUtil.file(bis,is,response);
    }

    @Override
    public R download() {
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String fileHost = ConstantPropertiesUtil.FILE_HOST;
        String file = OSSStringUtil.projecturl();
        OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        File fileUpload = new File(file);
        if (!fileUpload.exists()){
            fileUpload.mkdirs();
        }
        List userList = userDao.selectList(null);
        try {
            for (User user : userList) {
                String imageurl=user.getHeadImageurl();
                String name = OSSStringUtil.urltoname(imageurl);
                fileUpload = new File(file, name);
                System.out.println(fileUpload);
                if (fileUpload.exists()){
                    log.debug("文件已经存在!");
                      continue;
                }
                String filePath = OSSStringUtil.urltofilepath(imageurl, fileHost);
                String osskey = OSSStringUtil.osskey(fileHost, filePath, name);

                ossClient.getObject(new GetObjectRequest(bucketName,osskey), fileUpload);
            }
        }catch (Exception e){
            return  R.error().message(e.getMessage());
        }finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
        return    R.ok();
    }

    @Override
    public void exportExcelUser(HttpServletResponse response) {
        String file = OSSStringUtil.projecturl();
        System.out.println(file);
        List list = userDao.selectList(null);
        for (User user : list) {
            String imageurl = user.getHeadImageurl();
            String name = OSSStringUtil.urltoname(imageurl);
            user.setHeadImageurl(file+"/"+name);
        }
        System.out.println(list);
        EasyPoiUtils.exportExcel(list, "用户列表", "用户报表", User.class, "用户明细报表.xls", response);
    }

    @Override
    public List getUser() {
        List users = userDao.selectList(null);
        return users;
    }

    @Override
    public R importExcelUser(MultipartFile file) {
        ImportParams importParams = new ImportParams();
        // 数据处理
        importParams.setHeadRows(1);
        importParams.setTitleRows(1);
        // 需要验证
        importParams.setNeedVerfiy(false);
        try {
            ExcelImportResult result = ExcelImportUtil.importExcelMore(file.getInputStream(), User.class,
                    importParams);
            List commpanyList = result.getList();
            for (User commpany : commpanyList) {
                //保存到mysql
                int i = userDao.insert(commpany);
                if(i < 1){
                    log.error("保存失败");
                    return R.error().message("保存失败");
                }
              /*  //查出自增id
                TbCommpanyExample tbCommpanyExample = new TbCommpanyExample();
                tbCommpanyExample.createCriteria().andCompanyNameEqualTo(commpany.getCompanyName());
                long id = tbCommpanyMapper.selectByExample(tbCommpanyExample).get(0).getId();
                commpany.setId(id);*/
                //保存到redis
               // redisUtils.sSet("company",JSONObject.parseObject(JSONObject.toJSONString(commpany)));
            }
            log.info("从Excel导入数据一共 {} 行 ", commpanyList.size());
        } catch (Exception e) {
            log.error("导入失败:{}", e.getMessage());
            return  R.error().message("导入失败");
        }
        return R.ok().message("导入成功");

    }


}

9.编写控制层类,如果不用图片就忽略文件下载的部分

@RestController
@Api(value = "用户列表")
public class UserController {

    @Autowired
    UserService userService;
    
    @ApiOperation(value = "导入数据到数据库中")
    @PostMapping("/import/users")
    @ResponseBody
    public R importExcel(@RequestParam("file") MultipartFile file) {
        return userService.importExcelUser(file);
    }


    @ApiOperation(value = "导出数据到Excel表格")
    @GetMapping(value = "/export/users")
    public void exportUsers(HttpServletResponse response) {
          // userService.download();定时任务执行下载图片
           userService.exportExcelUser(response);

    }

    @ApiOperation(value = "浏览器按id文件下载")
    @GetMapping(value = "/downloads/{id}")
    public void logDownload(@PathVariable Integer id, HttpServletResponse response) throws Exception {
        userService.logDownload(id, response);
    }


   @ApiOperation(value = "按数据库url从阿里云中下载图片")
    @GetMapping("/loads")
    public R logDownload(){
        userService.download();
        return  R.ok();
    }
   // @PostConstruct // 加上该注解项目启动时就执行一次该方法
    @ApiOperation(value = "直接按照数据库中的url下载图片。")
    @GetMapping("/ossdownload")
    public R ossdownload() throws Exception {
        List users = userService.getUser();
        for (User user : users) {
            String headImageurl = user.getHeadImageurl();
            doloadimgUtil.download(headImageurl,user.getName());
        }
      return R.ok();
    }
}

10.工具类

public class OSSStringUtil {

    public static  String urltoname(String url){
        String name = url.substring(url.lastIndexOf("/") + 1);
        return  name;
    }

    public static  String urltofilepath(String url,String fileHost){

        String filePath = url.substring(url.indexOf(fileHost) + fileHost.length() + 1, url.lastIndexOf("/"));
        return  filePath;
    }
    public static  String osskey(String fileHost,String filePath,String name){

        String osskey = fileHost+"/"+filePath+"/"+name;
        return  osskey;
    }
    public static  String projecturl(){
        String property = System.getProperty("user.dir");//获取本项目路径
        String file = new File(property+"/"+"src/main/resources/static/imags").getAbsolutePath();
        return  file;
    }

    public static  void file(BufferedInputStream bis, InputStream is , HttpServletResponse response){
        try {
            bis = new BufferedInputStream(is);//把流放入缓存流
            OutputStream os = response.getOutputStream();//定义输出流的响应流。
            byte[] buffer = new byte[1024];//定义一个字节数
            int len;//记录每次读入到cbuf数组中的字符的个数
            while ((len = is.read(buffer)) != -1) {//开始输出
                os.write(buffer,0,len); //从数组中每次写出len个字符
            }
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

11.图中的返回类型R工具类,我就不贴了。

12.测试导入数据

Springboot2整合easypoi实现导入导出、OSS图片导出到Excel_第1张图片

Springboot2整合easypoi实现导入导出、OSS图片导出到Excel_第2张图片

Springboot2整合easypoi实现导入导出、OSS图片导出到Excel_第3张图片

文件导出,需要导出图片的话,需要把上传图片的url先保存到用户表中,然后再下载到本地,才能导入到Excel中。

数据导入到数据库中图片的路径肯定是空的。一般开发中会默认头像,用户设置头像了再保存url。测试的时候导出Excel不要在swagger中测试可以在浏览器中测试

Springboot2整合easypoi实现导入导出、OSS图片导出到Excel_第4张图片

有疑问请各位大佬留下珍贵的评论哦!

你可能感兴趣的:(springboot,OSS,java)