EasyExcel的使用
1 2 3
| <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.2.0-beta2</version>
|
表头的class(固定版)
JavaBean对应Excel的表头
com.alibaba.excel.annotation.@ExcelProperty
value=”表头的Name”,index=第几列
1 2 3 4 5 6
| import com.alibaba.excel.annotation; @lombok.Data public class ExcelTitle{ @ExcelProperty(value="第一列表头内容",index=0) private String firstTitle; }
|
这个与Excel对应的JavaBean即可以读取也可以写入
read
see
静态读
//DemoExceptionListener
1
| EasyExcel.read(excleFileName, ExcelTitle.class, new DemoExceptionListener()).sheet().doRead();
|
动态读
1 2 3 4
| AnalysisEventListener<Map<Integer,String>> listener; EasyExcel.read(excleFileName, listener).sheet().doRead();
List<Map<Integer, String>> listMap = EasyExcel.read(excleFileName).sheet().doReadSync();
|
write
静态写
1
| EasyExcel.write(writeFile,ExcelTitle.class).registerWriteHandler(getDefaultExcelHead()).sheet(0,sheetName).doWrite(List<?> data);
|
动态写
1 2 3 4
| ExcelWriter excelWriter; WriteSheet writeSheet = EasyExcel.writerSheet(sheetNo,sheetName).registerWriteHandler(getDefaultExcelHead()).head(dynamicHead).build(); excelWriter.write(List<?> data,writeSheet); excelWriter.finish();
|
自定义样式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public HorizontalCellStyleStrategy getDefaultExcelHead(){
WriteFont headWriteFont = new WriteFone(); headWriteFont.setBold(false); headWriteFont.setFontName("宋体"); headWriteFont.setFontHeightInPoints((short)11);
WriteCellStyle headWriteCellStyle = new WriteCellStyle(); headWriteCellStyle.setWriteFont(headWriteFont); headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex()); headWriteCellStyle.setWrapped(false); headWriteCellStyle.setBorderLeft(BorderStyle.THIN); headWriteCellStyle.setBorderRight(BorderStyle.THIN); headWriteCellStyle.setBorderTop(BorderStyle.THIN); headWriteCellStyle.setBorderBottom(BorderStyle.THIN); headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT); headWriteCellStyle.setLeftBorderColor(IndexedColors.WHITE1.getIndex()); headWriteCellStyle.setRightBorderColor(IndexedColors.WHITE1.getIndex()); headWriteCellStyle.setTopBorderColor(IndexedColors.WHITE1.getIndex()); headWriteCellStyle.setBottomBorderColor(IndexedColors.WHITE1.getIndex());
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); WriteFont contentWriteFont = new WriteFont();
contentWriteFont.setFontHeightInPoints((short)20); contentWriteCellStyle.setWriteFont(contentWriteFont); return new HorizontalCellStyleStrategy(headWriteCellStyle,contentWriteCellStyle); }
|