pom:引入easyexcel包
<!-- easyexcel 导入导出 --><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.7</version></dependency>
测试代码:
public static void main(String[] args) {String fileName = "D:\\excel"+ System.currentTimeMillis() + ".xlsx";// 头的策略WriteCellStyle headWriteCellStyle = new WriteCellStyle();// 内容的策略WriteCellStyle contentWriteCellStyle = new WriteCellStyle();//自动换行的代码contentWriteCellStyle.setWrapped(true);// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现HorizontalCellStyleStrategy horizontalCellStyleStrategy =new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);EasyExcel.write(fileName).registerWriteHandler(new CustomCellWriteHeightConfig())//添加excel单元格高度的计算策略,不需要改动.registerWriteHandler(new CustomCellWriteWeightConfig())//添加excel单元格长度的计算策略,不需要改动.registerWriteHandler(horizontalCellStyleStrategy)//换行// 这里放入动态头.head(head()).sheet("模板")// 当然这里数据也可以用 List<List<String>> 去传入.doWrite(data());}private static List<List<String>> head() {List<List<String>> list = new ArrayList<>();List<String> head0 = new ArrayList<>();head0.add("string" );List<String> head1 = new ArrayList<>();head1.add("number");List<String> head2 = new ArrayList<>();head2.add("date");list.add(head0);list.add(head1);list.add(head2);return list;}private static List<List<String>> data() {List<List<String>> list = new ArrayList<>();for (int i = 0; i < 10; i++) {List<String> stringList = new ArrayList<>();stringList.add("coum1");stringList.add("coum2");stringList.add("coum3");list.add(stringList);}return list;}
单元格高度和宽度的定义类:
package excelUtil;import com.alibaba.excel.write.style.row.AbstractRowHeightStyleStrategy;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.Row;import java.util.Iterator;//自适应行宽public class CustomCellWriteHeightConfig extends AbstractRowHeightStyleStrategy {/*** 默认高度*/private static final Integer DEFAULT_HEIGHT = 300;@Overrideprotected void setHeadColumnHeight(Row row, int relativeRowIndex) {}@Overrideprotected void setContentColumnHeight(Row row, int relativeRowIndex) {Iterator<Cell> cellIterator = row.cellIterator();if (!cellIterator.hasNext()) {return;}// 默认为 1行高度Integer maxHeight = 1;while (cellIterator.hasNext()) {Cell cell = cellIterator.next();switch (cell.getCellTypeEnum()) {case STRING:if (cell.getStringCellValue().indexOf("\n") != -1) {int length = cell.getStringCellValue().split("\n").length;maxHeight = Math.max(maxHeight, length);}break;default:break;}}row.setHeight((short) (maxHeight * DEFAULT_HEIGHT));}}
//自定义行高
package excelUtil;import com.alibaba.excel.metadata.CellData;import com.alibaba.excel.metadata.Head;import com.alibaba.excel.util.CollectionUtils;import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.Sheet;import java.util.HashMap;import java.util.List;import java.util.Map;public class CustomCellWriteWeightConfig extends AbstractColumnWidthStyleStrategy {private Map<Integer, Map<Integer, Integer>> CACHE = new HashMap<>();@Overrideprotected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer integer, Boolean isHead) {boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);if (needSetWidth) {Map<Integer, Integer> maxColumnWidthMap = CACHE.get(writeSheetHolder.getSheetNo());if (maxColumnWidthMap == null) {maxColumnWidthMap = new HashMap<>();CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);}Integer columnWidth = this.dataLength(cellDataList, cell, isHead);if (columnWidth >= 0) {if (columnWidth > 254) {columnWidth = 254;}Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());if (maxColumnWidth == null || columnWidth > maxColumnWidth) {maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);Sheet sheet = writeSheetHolder.getSheet();sheet.setColumnWidth(cell.getColumnIndex(), columnWidth * 256);}}}}/*** 计算长度** @param cellDataList* @param cell* @param isHead* @return*/private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {if (isHead) {return cell.getStringCellValue().getBytes().length;} else {//此处固定写成27,页面样式好看一点,否则直接计算,会自动一整行显示,不会换行--shenshuaireturn 27;}}}
最后导出效果:
