Skip to content

从数据库导出至excel的工具类

最近写了许多将数据从数据库导出至Excel的业务, 稍微整理个抽象类出来方便以后复用或拓展

只支持导出到只有一个sheet的Excel

java
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.util.List;

/**
 * Excel Sheet 导出工具
 *
 * @author Tomoto
 * @version 1.0 2022/7/14 10:51
 * @since 1.0
 */
public abstract class ExcelSheetExportHelper<T> {

    private Sheet sheet;

    /**
     * 获取表头
     *
     * @return 表头
     */
    public abstract String[] getHeader();

    /**
     * 获取文件名
     *
     * @return 文件名
     */
    public abstract String getFilename();

    /**
     * 填充行数据
     *
     * @param vo    vo
     * @param row
     * @param index 行索引
     */
    public abstract void fillRowData(T vo, Row row, int index);

    /**
     * 初始化
     * <p>
     * 设置表头格式, 填充表头
     *
     * @return workbook
     */
    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;
    }

    /**
     * 导出数据
     *
     * @param voList vo数组
     * @param index  起始index
     */
    public void exportData(List<T> voList, int index) {
        for (T vo : voList) {
            index++;
            fillRowData(vo, sheet.createRow(index), index);
        }
    }

}