当前位置:   article > 正文

Excel工具类以及OSS使用_com.alibaba.excel.metadata.celldata

com.alibaba.excel.metadata.celldata

1 maven依赖添加

  1. <!-- easyExcel -->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>easyexcel</artifactId>
  5. <version>2.2.8</version>
  6. </dependency>
  7. <!-- oss文件上传下载 -->
  8. <dependency>
  9. <groupId>com.aliyun.oss</groupId>
  10. <artifactId>aliyun-sdk-oss</artifactId>
  11. <version>3.10.2</version>
  12. </dependency>

2 实体类注解设置

  1. @Data
  2. @ApiModel("用户表")
  3. // 忽略未添加@ExcelProperty的字段
  4. @ExcelIgnoreUnannotated
  5. public class UserEntity {
  6. @TableId()
  7. @ApiModelProperty("主键id")
  8. @ExcelProperty(value = {"操作"}, index = 0, converter = NullValueConvert.class)
  9. private String id;
  10. @ApiModelProperty("家庭地址")
  11. private String address;
  12. }

3,NullValueConvert  格式转换

解释:当id字段为空时,excel上此字段显示空字符串,只需要实现Converter接口就可以了

  1. public class NullValueConvert implements Converter<String> {
  2. @Override
  3. public Class supportJavaTypeKey() {
  4. return String.class;
  5. }
  6. @Override
  7. public CellDataTypeEnum supportExcelTypeKey() {
  8. return CellDataTypeEnum.STRING;
  9. }
  10. @Override
  11. public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
  12. return cellData.getStringValue();
  13. }
  14. @Override
  15. public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
  16. return new CellData("");
  17. }
  18. }

eg: 数据库存储 0 代表否  1代表是 那么转换如下

  1. public class YesOrNoConvert implements Converter<Integer> {
  2. @Override
  3. public Class supportJavaTypeKey() {
  4. return Integer.class;
  5. }
  6. @Override
  7. public CellDataTypeEnum supportExcelTypeKey() {
  8. return CellDataTypeEnum.STRING;
  9. }
  10. @Override
  11. public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
  12. return "是".equals(cellData.getStringValue()) ? 1 : 0;
  13. }
  14. @Override
  15. public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
  16. return new CellData(value.equals(1) ? "是" : "否");
  17. }
  18. }

4, excel工具类编写

  1. import cn.hutool.core.io.IoUtil;
  2. import com.alibaba.excel.EasyExcelFactory;
  3. import com.alibaba.excel.metadata.CellData;
  4. import com.alibaba.excel.metadata.Head;
  5. import com.alibaba.excel.support.ExcelTypeEnum;
  6. import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
  7. import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
  8. import com.aliyun.oss.OSS;
  9. import com.aliyun.oss.OSSClientBuilder;
  10. import com.aliyun.oss.model.OSSObject;
  11. import com.config.AliyunConfig;
  12. import com.google.common.collect.Lists;
  13. import lombok.Cleanup;
  14. import lombok.extern.slf4j.Slf4j;
  15. import org.apache.poi.ss.usermodel.Cell;
  16. import org.apache.poi.ss.usermodel.Sheet;
  17. import org.springframework.stereotype.Component;
  18. import javax.annotation.Resource;
  19. import javax.servlet.http.HttpServletRequest;
  20. import javax.servlet.http.HttpServletResponse;
  21. import java.io.*;
  22. import java.net.URLEncoder;
  23. import java.time.LocalDateTime;
  24. import java.time.format.DateTimeFormatter;
  25. import java.util.List;
  26. /**
  27. * @author guiJia
  28. * @date 2021/5/31 19:41
  29. */
  30. @Component
  31. @Slf4j
  32. public class ExcelUtil {
  33. @Resource
  34. private HttpServletRequest request;
  35. @Resource
  36. private HttpServletResponse response;
  37. @Resource
  38. private AliyunConfig aliyunConfig;
  39. /**
  40. * 导出是生成 OutputStream
  41. */
  42. public static OutputStream getOutputStream(String fileName,
  43. HttpServletRequest request,
  44. HttpServletResponse response) throws IOException {
  45. if (null != request) {
  46. response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
  47. }
  48. response.setCharacterEncoding("utf-8");
  49. response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
  50. response.setHeader("content-type","application/x-msdownload");
  51. return response.getOutputStream();
  52. }
  53. /**
  54. * 导出excel
  55. * @param fileName 文件名
  56. * @param clazz 表头类
  57. * @param clazzList 数据列表
  58. */
  59. public void export(String fileName, Class<?> clazz, List<?> clazzList) {
  60. export(fileName, clazz, clazzList, Lists.newArrayList(), true);
  61. }
  62. /**
  63. * 导出excel
  64. */
  65. public void export(String fileName, Class<?> clazz, List<?> clazzList, List<String> excludeColumnList) {
  66. export(fileName, clazz, clazzList, excludeColumnList, false);
  67. }
  68. /**
  69. * 导出excel
  70. */
  71. private void export(String fileName, Class<?> clazz, List<?> clazzList, List<String> excludeColumnList, boolean isAuto) {
  72. try {
  73. fileName = fileName + DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now());
  74. fileName = URLEncoder.encode(fileName, "UTF-8");
  75. EasyExcelFactory.write(ExcelUtil.getOutputStream(fileName, request, response))
  76. .excelType(ExcelTypeEnum.XLSX)
  77. .head(clazz)
  78. .sheet()
  79. .registerWriteHandler(isAuto ? new ExcelWidthStyleStrategy() : null)
  80. .excludeColumnFiledNames(excludeColumnList)
  81. .doWrite(clazzList);
  82. } catch (Exception e) {
  83. log.error("下载失败:", e);
  84. }
  85. }
  86. /**
  87. * 自动设置列宽
  88. */
  89. public class ExcelWidthStyleStrategy extends AbstractColumnWidthStyleStrategy{
  90. @Override
  91. protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> list, Cell cell, Head head, Integer integer, Boolean aBoolean) {
  92. Sheet sheet = writeSheetHolder.getSheet();
  93. sheet.setColumnWidth(cell.getColumnIndex(), 3500);
  94. }
  95. }
  96. /**
  97. * 上传文件到oss平台
  98. *
  99. */
  100. public String uploadOss(String fileName, Class<?> clazz, List<?> clazzList) {
  101. fileName = fileName + DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now())
  102. + ExcelTypeEnum.XLSX.getValue();
  103. ByteArrayOutputStream out = new ByteArrayOutputStream();
  104. EasyExcelFactory.write(out)
  105. .excelType(ExcelTypeEnum.XLSX)
  106. .head(clazz)
  107. .sheet()
  108. .registerWriteHandler(new ExcelWidthStyleStrategy())
  109. .doWrite(clazzList);
  110. OSS ossClient = new OSSClientBuilder().build(aliyunConfig.getEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
  111. ossClient.putObject(aliyunConfig.getBucketName(), fileName, new ByteArrayInputStream(out.toByteArray()));
  112. ossClient.shutdown();
  113. return fileName;
  114. }
  115. /**
  116. * 登录oss
  117. */
  118. private InputStream openOss(String objectName) {
  119. OSS ossClient = new OSSClientBuilder().build(aliyunConfig.getEndpoint(), aliyunConfig.getAccessKeyId(), aliyunConfig.getAccessKeySecret());
  120. OSSObject ossObject = ossClient.getObject(aliyunConfig.getBucketName(), objectName);
  121. return ossObject.getObjectContent();
  122. }
  123. /**
  124. * 从oss下载文件
  125. */
  126. public void exportOss(String objectName) throws IOException {
  127. @Cleanup InputStream objectContent = openOss(objectName);
  128. String fileName = objectName.substring(objectName.lastIndexOf("/") + 1, objectName.lastIndexOf(ExcelTypeEnum.XLSX.getValue()));
  129. fileName = URLEncoder.encode(fileName, "UTF-8");
  130. @Cleanup OutputStream outputStream = ExcelUtil.getOutputStream(fileName, request, response);
  131. outputStream.write(IoUtil.readBytes(objectContent));
  132. }
  133. /**
  134. * 从oss下载图片
  135. */
  136. public void download(String objectName) throws IOException {
  137. @Cleanup InputStream objectContent = openOss(objectName);
  138. String fileName = objectName.substring(objectName.lastIndexOf("/") + 1, objectName.lastIndexOf("png") - 1);
  139. fileName = URLEncoder.encode(fileName, "UTF-8");
  140. @Cleanup OutputStream outputStream = getResponse(fileName);
  141. outputStream.write(IoUtil.readBytes(objectContent));
  142. }
  143. /**
  144. * 图片解析
  145. */
  146. private OutputStream getResponse(String fileName) throws IOException {
  147. fileName = URLEncoder.encode(fileName, "UTF-8");
  148. response.setHeader("content-disposition", "attachment;filename=" + fileName);
  149. response.setHeader("content-type", "image/png");
  150. return response.getOutputStream();
  151. }
  152. }

5,阿里云配置类

  1. @Data
  2. @Configuration
  3. @ConfigurationProperties(prefix = "aliyun.oss.file")
  4. public class AliyunConfig {
  5. private String endpoint;
  6. private String accessKeyId;
  7. private String accessKeySecret;
  8. private String bucketName;
  9. }

6,使用以及测试

excelUtil.export("用户列表导出", UserEntity.class, userEntityList);

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号