推荐篇:原来阿里也对excel情有独钟( 二 )


注:导入和导出时使用到的User实体类而不是普通的实体类,需要添加该包下的注解,才可在导入或导出的时候和excel中的列映射;
如果实体类中存在许多字段而导出时有些字段不需要 就需要在该字段上添加@注解;就不会使用该字段;如果该字段不使用并且也没有添加的任何注解,那么导出时也会将该字段导出到excel表格中;
import com.alibaba.excel.annotation.ExcelProperty;import java.math.BigDecimal;/*** @author Mr.Gu* @date 2020/10/21 9:20* @function :**/public class User {@ExcelProperty(value = "http://www.kingceram.com/post/编号",index = 0)private Integer number;@ExcelProperty(value = "http://www.kingceram.com/post/姓名",index = 1)private String name;@ExcelProperty(value = "http://www.kingceram.com/post/性别",index = 2)private String sex;@ExcelProperty(value = "http://www.kingceram.com/post/年龄",index = 3)private Integer age;@ExcelProperty(value = "http://www.kingceram.com/post/分数",index = 4)private BigDecimal score;//getter/setter方法
最后,使用该工具类导出的excel如下:
非常简单,好用的一个excel工具类 。记录完成 。
设置单元格自适应宽度:
import com.alibaba.excel.enums.CellDataTypeEnum;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 java.util.HashMap;import java.util.List;import java.util.Map;public class ExcelCellWriteHandler extends AbstractColumnWidthStyleStrategy {private Map> CACHE = new HashMap<>();@Overrideprotected void setColumnWidth(WriteSheetHolder writeSheetHolder, List cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);if (needSetWidth) {Map 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 > 255) {columnWidth = 255;}Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());if (maxColumnWidth == null || columnWidth > maxColumnWidth) {maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);}}}}private Integer dataLength(List cellDataList, Cell cell, Boolean isHead) {if (isHead) {return cell.getStringCellValue().getBytes().length;} else {CellData cellData = http://www.kingceram.com/post/cellDataList.get(0);CellDataTypeEnum type = cellData.getType();if (type == null) {return -1;} else {switch (type) {case STRING:return cellData.getStringValue().getBytes().length;case BOOLEAN:return cellData.getBooleanValue().toString().getBytes().length;case NUMBER:return cellData.getNumberValue().toString().getBytes().length;default:return -1;}}}}}
将该类作为配置类放到项目中;
【推荐篇:原来阿里也对excel情有独钟】使用方式: