写入图片

将数据中的图片写入excel中

实体类

  1. @Data
  2. @ColumnWidth(100 / 8)
  3. @ContentRowHeight(100)
  4. public class ImageData {
  5. private File file;
  6. private InputStream inputStream;
  7. @ExcelProperty(converter = StringToImageConverter.class)
  8. private String path;
  9. private byte[] byteArray;
  10. private URL url;
  11. }

@ColumnWidth(100 / 8) :定义单元格的宽度
@ContentRowHeight(100):定义每一行的高度

转换类

  1. public class StringToImageConverter implements Converter<String> {
  2. @Override
  3. public Class supportJavaTypeKey() {
  4. return String.class;
  5. }
  6. @Override
  7. public CellDataTypeEnum supportExcelTypeKey() {
  8. return CellDataTypeEnum.IMAGE;
  9. }
  10. @Override
  11. public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
  12. throw new UnsupportedOperationException("不支持图片读取");
  13. }
  14. @Override
  15. public CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
  16. return new CellData(FileUtils.readFileToByteArray(new File(value)));
  17. }
  18. }

工具类

  1. package com.example.exceltools.write;
  2. import com.alibaba.excel.exception.ExcelAnalysisException;
  3. import com.alibaba.excel.util.IoUtils;
  4. import java.io.*;
  5. /**
  6. * @author xupu
  7. * @description
  8. * @date 2021/8/31 15:55:25
  9. */
  10. public class FileUtils {
  11. public static final int EOF = -1;
  12. private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
  13. private static final int WRITE_BUFF_SIZE = 8192;
  14. private FileUtils() {}
  15. public static byte[] readFileToByteArray(final File file) throws IOException {
  16. try (InputStream in = openInputStream(file)) {
  17. final long fileLength = file.length();
  18. return fileLength > 0 ? IoUtils.toByteArray(in, (int) fileLength) : IoUtils.toByteArray(in);
  19. }
  20. }
  21. public static FileInputStream openInputStream(final File file) throws IOException {
  22. if (file.exists()) {
  23. if (file.isDirectory()) {
  24. throw new IOException("File '" + file + "' exists but is a directory");
  25. }
  26. if (!file.canRead()) {
  27. throw new IOException("File '" + file + "' cannot be read");
  28. }
  29. } else {
  30. throw new FileNotFoundException("File '" + file + "' does not exist");
  31. }
  32. return new FileInputStream(file);
  33. }
  34. public static void writeToFile(File file, InputStream inputStream) {
  35. OutputStream outputStream = null;
  36. try {
  37. outputStream = new FileOutputStream(file);
  38. int bytesRead;
  39. byte[] buffer = new byte[WRITE_BUFF_SIZE];
  40. while ((bytesRead = inputStream.read(buffer, 0, WRITE_BUFF_SIZE)) != -1) {
  41. outputStream.write(buffer, 0, bytesRead);
  42. }
  43. } catch (Exception e) {
  44. throw new ExcelAnalysisException("Can not create temporary file!", e);
  45. } finally {
  46. if (outputStream != null) {
  47. try {
  48. outputStream.close();
  49. } catch (IOException e) {
  50. throw new ExcelAnalysisException("Can not close 'outputStream'!", e);
  51. }
  52. }
  53. if (inputStream != null) {
  54. try {
  55. inputStream.close();
  56. } catch (IOException e) {
  57. throw new ExcelAnalysisException("Can not close 'inputStream'", e);
  58. }
  59. }
  60. }
  61. }
  62. public static byte[] toByteArray(final InputStream input) throws IOException {
  63. final ByteArrayOutputStream output = new ByteArrayOutputStream();
  64. try {
  65. copy(input, output);
  66. return output.toByteArray();
  67. } finally {
  68. output.toByteArray();
  69. }
  70. }
  71. /**
  72. * Gets the contents of an InputStream as a byte[].
  73. *
  74. * @param input
  75. * @param size
  76. *
  77. * @return
  78. *
  79. * @throws IOException
  80. */
  81. public static byte[] toByteArray(final InputStream input, final int size) throws IOException {
  82. if (size < 0) {
  83. throw new IllegalArgumentException("Size must be equal or greater than zero: " + size);
  84. }
  85. if (size == 0) {
  86. return new byte[0];
  87. }
  88. final byte[] data = new byte[size];
  89. int offset = 0;
  90. int read;
  91. while (offset < size && (read = input.read(data, offset, size - offset)) != EOF) {
  92. offset += read;
  93. }
  94. if (offset != size) {
  95. throw new IOException("Unexpected read size. current: " + offset + ", expected: " + size);
  96. }
  97. return data;
  98. }
  99. /**
  100. * Copies bytes
  101. *
  102. * @param input
  103. * @param output
  104. *
  105. * @return
  106. *
  107. * @throws IOException
  108. */
  109. public static int copy(final InputStream input, final OutputStream output) throws IOException {
  110. long count = 0;
  111. int n;
  112. byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
  113. while (EOF != (n = input.read(buffer))) {
  114. output.write(buffer, 0, n);
  115. count += n;
  116. }
  117. if (count > Integer.MAX_VALUE) {
  118. return -1;
  119. }
  120. return (int) count;
  121. }
  122. }

实现代码

  1. @SneakyThrows
  2. private static void imageWrite(String filePath, String projectPath) {
  3. // 如果使用流 记得关闭
  4. InputStream inputStream = null;
  5. try {
  6. List<ImageData> list = new ArrayList<>();
  7. String imagePath = projectPath + File.separator + "img" + File.separator + "img.jpg";
  8. // 放入五种类型的图片 实际使用只要选一种即可
  9. ImageData imageData = new ImageData();
  10. imageData.setByteArray(FileUtils.readFileToByteArray(new File(imagePath)));
  11. imageData.setFile(new File(imagePath));
  12. inputStream = FileUtils.openInputStream(new File(imagePath));
  13. imageData.setInputStream(inputStream);
  14. imageData.setPath(imagePath);
  15. imageData.setUrl(new URL("https://images.unsplash.com/photo-1630321133789-10b000def0cd?ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyfHx8ZW58MHx8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"));
  16. list.add(imageData);
  17. EasyExcel.write(filePath, ImageData.class).sheet().doWrite(list);
  18. } finally {
  19. if (inputStream != null) {
  20. inputStream.close();
  21. }
  22. }
  23. }

根据模板文件进行写入

设置一个模板文件,以该文件 为模板进行写入,新增sheet在模板之后

  1. private static void templateWrite(String filePath, String tempPath, List<WriteData> list) {
  2. EasyExcel.write(filePath, WriteData.class).withTemplate(tempPath).sheet("模板文件导出").doWrite(list);
  3. }

列宽、行高

设置导出的excel数据的列宽、行高属性

  1. @Data
  2. @ContentRowHeight(10)
  3. @HeadRowHeight(20)
  4. @ColumnWidth(25)
  5. public class WidthAndHeightData {
  6. @ExcelProperty("字符串标题")
  7. private String string;
  8. @ExcelProperty("日期标题")
  9. private Date date;
  10. /**
  11. * 宽度为50
  12. */
  13. @ColumnWidth(50)
  14. @ExcelProperty("数字标题")
  15. private Double doubleData;
  16. }

@ContentRowHeight(10) :定义每一行的高度
@HeadRowHeight(20) :定义头部每一行的高度
@ColumnWidth(25):定义每一列的宽度,可以设置总体,也可以单独设置

自定义样式

对于导出的excel,我们可以对其样式进行一些简单的设置

注解的方式

  1. @Data
  2. // 头背景设置成红色 IndexedColors.RED.getIndex()
  3. @HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 5)
  4. // 头字体设置成20
  5. @HeadFontStyle(fontHeightInPoints = 16)
  6. // 内容的背景设置成绿色 IndexedColors.GREEN.getIndex()
  7. @ContentStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 4)
  8. // 内容字体设置成20
  9. @ContentFontStyle(fontHeightInPoints = 20)
  10. public class CustomStyleData {
  11. // 字符串的头背景设置成粉红 IndexedColors.PINK.getIndex()
  12. @HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 14)
  13. // 字符串的头字体设置成20
  14. @HeadFontStyle(fontHeightInPoints = 30)
  15. // 字符串的内容的背景设置成天蓝 IndexedColors.SKY_BLUE.getIndex()
  16. @ContentStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 40)
  17. // 字符串的内容字体设置成20
  18. @ContentFontStyle(fontHeightInPoints = 30)
  19. @ExcelProperty("字符串标题")
  20. private String string;
  21. @ExcelProperty("日期标题")
  22. private Date date;
  23. @ExcelProperty("数字标题")
  24. private Double doubleData;
  25. }

编码方式实现

  1. private static void customStyleByCode(String filePath, List<CustomStyleData> customStyleData) {
  2. // 头的策略
  3. WriteCellStyle headWriteCellStyle = new WriteCellStyle();
  4. headWriteCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
  5. WriteFont headWriteFont = new WriteFont();
  6. headWriteFont.setFontHeightInPoints((short) 20);
  7. headWriteCellStyle.setWriteFont(headWriteFont);
  8. // 内容的策略
  9. WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
  10. // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
  11. contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
  12. // 背景绿色
  13. contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
  14. WriteFont contentWriteFont = new WriteFont();
  15. // 字体大小
  16. contentWriteFont.setFontHeightInPoints((short) 20);
  17. contentWriteCellStyle.setWriteFont(contentWriteFont);
  18. // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
  19. HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
  20. // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
  21. EasyExcel.write(filePath, CustomStyleData.class)
  22. .registerWriteHandler(horizontalCellStyleStrategy)
  23. .sheet("模板")
  24. .doWrite(customStyleData);
  25. }

但是一般不会搞的这么花里胡哨的,简单的功能就足够使用了