pom:引入easyexcel包

    1. <!-- easyexcel 导入导出 -->
    2. <dependency>
    3. <groupId>com.alibaba</groupId>
    4. <artifactId>easyexcel</artifactId>
    5. <version>2.2.7</version>
    6. </dependency>

    测试代码:

    1. public static void main(String[] args) {
    2. String fileName = "D:\\excel"+ System.currentTimeMillis() + ".xlsx";
    3. // 头的策略
    4. WriteCellStyle headWriteCellStyle = new WriteCellStyle();
    5. // 内容的策略
    6. WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
    7. //自动换行的代码
    8. contentWriteCellStyle.setWrapped(true);
    9. // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
    10. HorizontalCellStyleStrategy horizontalCellStyleStrategy =
    11. new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    12. EasyExcel.write(fileName)
    13. .registerWriteHandler(new CustomCellWriteHeightConfig())//添加excel单元格高度的计算策略,不需要改动
    14. .registerWriteHandler(new CustomCellWriteWeightConfig())//添加excel单元格长度的计算策略,不需要改动
    15. .registerWriteHandler(horizontalCellStyleStrategy)//换行
    16. // 这里放入动态头
    17. .head(head()).sheet("模板")
    18. // 当然这里数据也可以用 List<List<String>> 去传入
    19. .doWrite(data());
    20. }
    21. private static List<List<String>> head() {
    22. List<List<String>> list = new ArrayList<>();
    23. List<String> head0 = new ArrayList<>();
    24. head0.add("string" );
    25. List<String> head1 = new ArrayList<>();
    26. head1.add("number");
    27. List<String> head2 = new ArrayList<>();
    28. head2.add("date");
    29. list.add(head0);
    30. list.add(head1);
    31. list.add(head2);
    32. return list;
    33. }
    34. private static List<List<String>> data() {
    35. List<List<String>> list = new ArrayList<>();
    36. for (int i = 0; i < 10; i++) {
    37. List<String> stringList = new ArrayList<>();
    38. stringList.add("coum1");
    39. stringList.add("coum2");
    40. stringList.add("coum3");
    41. list.add(stringList);
    42. }
    43. return list;
    44. }

    单元格高度和宽度的定义类:

    1. package excelUtil;
    2. import com.alibaba.excel.write.style.row.AbstractRowHeightStyleStrategy;
    3. import org.apache.poi.ss.usermodel.Cell;
    4. import org.apache.poi.ss.usermodel.Row;
    5. import java.util.Iterator;
    6. //自适应行宽
    7. public class CustomCellWriteHeightConfig extends AbstractRowHeightStyleStrategy {
    8. /**
    9. * 默认高度
    10. */
    11. private static final Integer DEFAULT_HEIGHT = 300;
    12. @Override
    13. protected void setHeadColumnHeight(Row row, int relativeRowIndex) {
    14. }
    15. @Override
    16. protected void setContentColumnHeight(Row row, int relativeRowIndex) {
    17. Iterator<Cell> cellIterator = row.cellIterator();
    18. if (!cellIterator.hasNext()) {
    19. return;
    20. }
    21. // 默认为 1行高度
    22. Integer maxHeight = 1;
    23. while (cellIterator.hasNext()) {
    24. Cell cell = cellIterator.next();
    25. switch (cell.getCellTypeEnum()) {
    26. case STRING:
    27. if (cell.getStringCellValue().indexOf("\n") != -1) {
    28. int length = cell.getStringCellValue().split("\n").length;
    29. maxHeight = Math.max(maxHeight, length);
    30. }
    31. break;
    32. default:
    33. break;
    34. }
    35. }
    36. row.setHeight((short) (maxHeight * DEFAULT_HEIGHT));
    37. }
    38. }

    //自定义行高

    1. package excelUtil;
    2. import com.alibaba.excel.metadata.CellData;
    3. import com.alibaba.excel.metadata.Head;
    4. import com.alibaba.excel.util.CollectionUtils;
    5. import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
    6. import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
    7. import org.apache.poi.ss.usermodel.Cell;
    8. import org.apache.poi.ss.usermodel.Sheet;
    9. import java.util.HashMap;
    10. import java.util.List;
    11. import java.util.Map;
    12. public class CustomCellWriteWeightConfig extends AbstractColumnWidthStyleStrategy {
    13. private Map<Integer, Map<Integer, Integer>> CACHE = new HashMap<>();
    14. @Override
    15. protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer integer, Boolean isHead) {
    16. boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
    17. if (needSetWidth) {
    18. Map<Integer, Integer> maxColumnWidthMap = CACHE.get(writeSheetHolder.getSheetNo());
    19. if (maxColumnWidthMap == null) {
    20. maxColumnWidthMap = new HashMap<>();
    21. CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
    22. }
    23. Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
    24. if (columnWidth >= 0) {
    25. if (columnWidth > 254) {
    26. columnWidth = 254;
    27. }
    28. Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
    29. if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
    30. maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
    31. Sheet sheet = writeSheetHolder.getSheet();
    32. sheet.setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
    33. }
    34. }
    35. }
    36. }
    37. /**
    38. * 计算长度
    39. *
    40. * @param cellDataList
    41. * @param cell
    42. * @param isHead
    43. * @return
    44. */
    45. private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {
    46. if (isHead) {
    47. return cell.getStringCellValue().getBytes().length;
    48. } else {
    49. //此处固定写成27,页面样式好看一点,否则直接计算,会自动一整行显示,不会换行--shenshuai
    50. return 27;
    51. }
    52. }
    53. }

    最后导出效果:
    image.png