最近写了许多将数据从数据库导出至Excel的业务, 稍微整理个抽象类出来方便以后复用或拓展
只支持导出到只有一个sheet的Excel
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import java.util.List;
public abstract class ExcelSheetExportHelper<T> {
private Sheet sheet;
public abstract String[] getHeader();
public abstract String getFilename();
public abstract void fillRowData(T vo, Row row, int index);
public Workbook init() { Workbook workbook = new SXSSFWorkbook(); sheet = workbook.createSheet(getFilename());
sheet.autoSizeColumn(1, true); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
Row row = sheet.createRow(0); for (int i = 0; i < getHeader().length; i++) { Cell hCell = row.createCell(i); hCell.setCellStyle(cellStyle); hCell.setCellValue(getHeader()[i]); } return workbook; }
public void exportData(List<T> voList, int index) { for (T vo : voList) { index++; fillRowData(vo, sheet.createRow(index), index); } }
}
|