Excel导出

ExcelData实体类
package com.haierfinancial.firefly.util;

import java.util.List;

public class ExcelData {

    private static final long serialVersionUID = 4444017239100620999L;
    private List<String> titles;
    private List<String> subTitles;
    private List<List<Object>> rows;
    private String name;
    private List<ExcelMergedRegion> excelMergedRegionList;
    public ExcelData() {
    }

    public List<String> getTitles() {
        return this.titles;
    }

    public void setTitles(List<String> titles) {
        this.titles = titles;
    }

    public List<List<Object>> getRows() {
        return this.rows;
    }

    public void setRows(List<List<Object>> rows) {
        this.rows = rows;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getSubTitles() {
        return subTitles;
    }

    public void setSubTitles(List<String> subTitles) {
        this.subTitles = subTitles;
    }

    public List<ExcelMergedRegion> getExcelMergedRegionList() {
        return excelMergedRegionList;
    }

    public void setExcelMergedRegionList(List<ExcelMergedRegion> excelMergedRegionList) {
        this.excelMergedRegionList = excelMergedRegionList;
    }
}

合并单元格实体类

package com.haierfinancial.firefly.util;

import lombok.Data;

@Data
public class ExcelMergedRegion {
    private int firstRow;
    private int lastRow;
    private int firstCol;
    private int lastCol;

    public ExcelMergedRegion(int firstRow, int lastRow, int firstCol, int lastCol) {
        this.firstRow = firstRow;
        this.lastRow = lastRow;
        this.firstCol = firstCol;
        this.lastCol = lastCol;
    }
}

导出工具类ExportExcelUtils(正常导出,合并单元格导出,设置隐藏列导出,设置单元格宽度导出)

package com.haierfinancial.firefly.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder;

import javax.servlet.http.HttpServletResponse;
import java.awt.Color;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@Slf4j
public class ExportExcelUtils {

    public ExportExcelUtils() {
    }

    /**
     * 正常导出
     * @param response
     * @param fileName
     * @param data
     * @throws Exception
     */
    public static void exportExcel(HttpServletResponse response, String fileName, ExcelData data) throws Exception {
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        response.setContentType("application/x-download");
        response.setCharacterEncoding("utf-8");
        exportExcel(data, response);
    }

    public static void exportExcel(ExcelData data, HttpServletResponse response) {


        try (XSSFWorkbook wb = new XSSFWorkbook(); OutputStream out = response.getOutputStream()){
            String sheetName = data.getName();
            if (null == sheetName) {
                sheetName = "Sheet1";
            }

            XSSFSheet sheet = wb.createSheet(sheetName);
            if (CollectionUtils.isNotEmpty(data.getSubTitles()) && CollectionUtils.isNotEmpty(data.getExcelMergedRegionList())){
                writeExcelContainsSubTitles(wb, sheet, data);
            }else{
                writeExcel(wb, sheet, data);
            }
            wb.write(out);
        } catch (Exception e) {
            log.error("异常原因:{}",e);
        }

    }


    /**
     * 设置单元格宽度导出
     * @param response
     * @param fileName
     * @param data
     * @throws Exception
     */
    public static void exportExcelSetWidth(HttpServletResponse response, String fileName, ExcelData data, Map<Integer,Integer> widthMap) throws Exception {
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        response.setContentType("application/x-download");
        response.setCharacterEncoding("utf-8");
        exportExcelSetWidth(data, response,widthMap);
    }

    public static void exportExcelSetWidth(ExcelData data, HttpServletResponse response,Map<Integer,Integer> widthMap) {


        try (XSSFWorkbook wb = new XSSFWorkbook(); OutputStream out = response.getOutputStream()){
            String sheetName = data.getName();
            if (null == sheetName) {
                sheetName = "Sheet1";
            }
            XSSFSheet sheet = wb.createSheet(sheetName);
            //设置单元格宽度
            if(Objects.nonNull(widthMap) && widthMap.size() > 0){
                for(Integer key : widthMap.keySet()){
                    sheet.setColumnWidth(key, widthMap.get(key));
                }
            }
            if (CollectionUtils.isNotEmpty(data.getSubTitles()) && CollectionUtils.isNotEmpty(data.getExcelMergedRegionList())){
                writeExcelContainsSubTitles(wb, sheet, data);
            }else{
                writeExcel(wb, sheet, data);
            }
            wb.write(out);
        } catch (Exception e) {
            log.error("异常原因:{}",e);
        }

    }

    /**
     * 设置隐藏列导出
     * @param response
     * @param fileName
     * @param data
     * @param colIndex
     * @throws Exception
     */
    public static void exportExcelHideCol(HttpServletResponse response, String fileName, ExcelData data,int colIndex ) throws Exception {
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        response.setContentType("application/x-download");
        response.setCharacterEncoding("utf-8");
        exportExcelHideCol(data, response, colIndex);
    }

    public static void exportExcelHideCol(ExcelData data, HttpServletResponse response,int colIndex) {

        try (XSSFWorkbook wb = new XSSFWorkbook();OutputStream out = response.getOutputStream()){
            String sheetName = data.getName();
            if (null == sheetName) {
                sheetName = "Sheet1";
            }

            XSSFSheet sheet = wb.createSheet(sheetName);
            writeExcel(wb, sheet, data);
//            sheet.setColumnWidth(colIndex,0);
            //设置列隐藏
            sheet.getColumnHelper().setColHidden((long)colIndex, true);
            wb.write(out);
        } catch (Exception e) {
            log.error("异常原因:{}",e);
        }

    }

    public static void exportExcels(HttpServletResponse response, String fileName, List<ExcelData> dataList) throws Exception {
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        response.setContentType("application/x-download");
        response.setCharacterEncoding("utf-8");
        exportExcels(dataList, response.getOutputStream());
    }

    public static void exportExcels(List<ExcelData> dataList, OutputStream out) throws Exception {
        XSSFWorkbook wb = new XSSFWorkbook();
        try {
            for(int i =0; i<dataList.size();i++){
                ExcelData data = dataList.get(i);
                String sheetName = data.getName();
                if (null == sheetName) {
                    sheetName = "Sheet"+(i+1);
                }

                XSSFSheet sheet = wb.createSheet();
                wb.setSheetName(i,sheetName);
                writeExcel(wb, sheet, data);
            }
            wb.write(out);
        } finally {
            wb.close();
            out.close();
        }
    }

    private static void writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data) {
        int rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles());
        writeRowsToExcel(wb, sheet, data.getRows(), rowIndex);
    }

    private static void writeExcelContainsSubTitles(XSSFWorkbook wb, Sheet sheet, ExcelData data) {
        int rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles());
        rowIndex = writeSubTitlesToExcel(wb, sheet, data.getSubTitles(), rowIndex,data.getExcelMergedRegionList());
        writeRowsToExcel(wb, sheet, data.getRows(), rowIndex);
    }

    private static int writeSubTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List<String> titles, int rowIndex,List<ExcelMergedRegion> excelMergedRegionList) {
        Font titleFont = wb.createFont();
        titleFont.setFontName("simsun");
        titleFont.setBold(true);
        titleFont.setColor(IndexedColors.BLACK.index);
        XSSFCellStyle titleStyle = wb.createCellStyle();
        titleStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192)));
        titleStyle.setFont(titleFont);
        setBorder(titleStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
        Row titleRow = sheet.createRow(rowIndex);
        int colIndex = 0;

        for (Iterator var8 = titles.iterator(); var8.hasNext(); ++colIndex) {
            String field = (String) var8.next();
            Cell cell = titleRow.createCell(colIndex);
            cell.setCellValue(field);
            cell.setCellStyle(titleStyle);
        }
        if (CollectionUtils.isNotEmpty(excelMergedRegionList)){
            for (ExcelMergedRegion region : excelMergedRegionList) {
                sheet.addMergedRegion(new CellRangeAddress(region.getFirstRow(),region.getLastRow(),region.getFirstCol(),region.getLastCol()));
            }
        }
        return rowIndex + 1;
    }

    private static int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List<String> titles) {
        int rowIndex = 0;
        Font titleFont = wb.createFont();
        titleFont.setFontName("simsun");
        titleFont.setBold(true);
        titleFont.setColor(IndexedColors.BLACK.index);
        XSSFCellStyle titleStyle = wb.createCellStyle();
        titleStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192)));
        titleStyle.setFont(titleFont);
        setBorder(titleStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
        Row titleRow = sheet.createRow(rowIndex);
        int colIndex = 0;

        for(Iterator var8 = titles.iterator(); var8.hasNext(); ++colIndex) {
            String field = (String)var8.next();
            Cell cell = titleRow.createCell(colIndex);
            cell.setCellValue(field);
            cell.setCellStyle(titleStyle);
        }

        rowIndex = rowIndex + 1;
        return rowIndex;
    }

    private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex) {
        DecimalFormat df = new DecimalFormat("#,###");
        Font dataFont = wb.createFont();
        dataFont.setFontName("simsun");
        dataFont.setColor(IndexedColors.BLACK.index);
        XSSFCellStyle dataStyle = wb.createCellStyle();
        dataStyle.setFont(dataFont);
        setBorder(dataStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));

        for(Iterator var8 = rows.iterator(); var8.hasNext(); ++rowIndex) {
            List<Object> rowData = (List)var8.next();
            Row dataRow = sheet.createRow(rowIndex);
            int colIndex = 0;

            for(Iterator var11 = rowData.iterator(); var11.hasNext(); ++colIndex) {
                Object cellData = var11.next();
                Cell cell = dataRow.createCell(colIndex);
                if (cellData != null) {
                    cell.setCellValue(cellData.toString());
                    if (cellData instanceof Integer) {
                        cell.setCellValue(df.format(cellData));
                    }
                } else {
                    cell.setCellValue("");
                }

                cell.setCellStyle(dataStyle);
            }
        }

        return rowIndex;
    }

    private static void autoSizeColumns(Sheet sheet, int columnNumber) {
        for(int i = 0; i < columnNumber; ++i) {
            int orgWidth = sheet.getColumnWidth(i);
            sheet.autoSizeColumn(i, true);
            int newWidth = sheet.getColumnWidth(i) + 100;
            if (newWidth > orgWidth) {
                sheet.setColumnWidth(i, newWidth);
            } else {
                sheet.setColumnWidth(i, orgWidth);
            }
        }

    }

    private static void setBorder(XSSFCellStyle style, BorderStyle border, XSSFColor color) {
        style.setBorderTop(border);
        style.setBorderLeft(border);
        style.setBorderRight(border);
        style.setBorderBottom(border);
        style.setBorderColor(XSSFCellBorder.BorderSide.TOP, color);
        style.setBorderColor(XSSFCellBorder.BorderSide.LEFT, color);
        style.setBorderColor(XSSFCellBorder.BorderSide.RIGHT, color);
        style.setBorderColor(XSSFCellBorder.BorderSide.BOTTOM, color);
        //垂直居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);
    }
}

设置宽度导出调用

Page<ImportData> page = new Page<>(1, 65535);
        IPage<ImportData> importDataIPage = this.getBaseMapper().queryAll(page, param);
        List<ImportData> list = importDataIPage.getRecords();
        if(CollectionUtils.isNotEmpty(list)){
            ExcelData data = new ExcelData();
            String name = "人员预算导出.xlsx";
            data.setName(name);
            List<String> titles = new ArrayList();
            titles.add("指标自定义编码");
            titles.add("指标自定义名称");
            titles.add("年份");
            titles.add("期间");
            titles.add("组织名称");
            titles.add("人员名称");
            titles.add("金额");
            titles.add("单位");
            data.setTitles(titles);

            List<List<Object>> rows = new ArrayList();
            list.forEach(u ->{
                List<Object> row = new ArrayList();
                row.add(u.getDefineCode());
                row.add(u.getDefineName());
                row.add(u.getYearNumberName());
                row.add(u.getTermName());
                row.add(u.getOrgName());
                row.add(u.getEmpName());
                row.add(Objects.nonNull(u.getCoreIndicatorTargetValue())?u.getCoreIndicatorTargetValue().setScale(0, BigDecimal.ROUND_HALF_UP):0);
                row.add(Objects.nonNull(DefineUnitEnum.getByCode(u.getDefineUnit()))?DefineUnitEnum.getByCode(u.getDefineUnit()).getValue():"");
                rows.add(row);
            });
            data.setRows(rows);

            try {
                Map<Integer,Integer> widthMap = new HashMap<>();
                widthMap.put(0,5300);
                widthMap.put(1,5000);
                ExportExcelUtils.exportExcelSetWidth(response, name, data,widthMap);
            } catch (Exception e) {
                log.error("异常原因:{}",e);
            }
        }

合并单元格导出

/**
     * 空间管理实际分配到人明细年度导出
     * @param response
     * @param criteria
     */
    private void exportOneTwoYear(HttpServletResponse response, AllocateActualDetailCriteria criteria) {
        criteria.setCurrentPage(1);
        criteria.setPageSize(65535);
        IPage<OneTwoDistributionReportYearModel> iPage = queryOneTwoDistributionYearReport(criteria);
        if (Objects.nonNull(iPage) && !CollectionUtils.isEmpty(iPage.getRecords())) {
            ExcelData data = new ExcelData();
            String name = "实际分配到人明细年度导出.xlsx";
            data.setName(name);
            List<String> titles = new ArrayList<>();
            titles.add("年度");
            titles.add("周期");
            titles.add("一级部门");
            titles.add("二级部门");
            titles.add("三级部门");
            titles.add("员工编号");
            titles.add("员工姓名");
            titles.add("本次兑现合计");
            titles.add("");
            titles.add("");
            titles.add("");
            titles.add("季度已兑现合计");
            titles.add("本次对赌");
            titles.add("本次兑现合计");
            titles.add("一次分配");
            titles.add("");
            titles.add("");
            titles.add("");
            titles.add("");
            titles.add("");
            titles.add("");
            titles.add("");
            titles.add("二次分配");
            titles.add("");
            titles.add("");
            titles.add("对赌部分");
            titles.add("");
            titles.add("");
            titles.add("激励说明");
            data.setTitles(titles);
            data.setSubTitles(getSubYearTitleRowYear());
            data.setExcelMergedRegionList(fillYearMergedRegion());
            List<List<Object>> rows = new ArrayList<>();
            iPage.getRecords().forEach(u -> {
                try {
                    List<Object> row = new ArrayList<>();
                    row.add(u.getYear().toString());
                    row.add(u.getCycle());
                    row.add(u.getDeptName());
                    row.add(u.getSecondDeptName());
                    row.add(u.getThirdDeptName());
                    row.add(u.getEmployeeNo());
                    row.add(u.getEmployeeName());
                    row.add(ExcelUtil.formatComma(u.getActualYearAmount()));
                    row.add(ExcelUtil.formatComma(u.getOneAmount()));
                    row.add(ExcelUtil.formatComma(u.getTwoAmount()));
                    row.add(ExcelUtil.formatComma(u.getAssetAmount()));
                    row.add(ExcelUtil.formatComma(u.getQuarterYearAmount()));
                    row.add(ExcelUtil.formatComma(u.getCurrentAssetAmount()));
                    row.add(ExcelUtil.formatComma(u.getQuarterActualAmount()));
                    row.add(ExcelUtil.formatComma(u.getConversionAmount()));
                    row.add(u.getPublicDiscussion());
                    row.add(u.getAdjustCoefficient());
                    row.add(u.getCashCoefficient());
                    row.add(ExcelUtil.formatComma(u.getConversionAmountThisCash()));
                    row.add(ExcelUtil.formatComma(u.getOtherOneAmount()));
                    row.add(ExcelUtil.formatComma(u.getOneYearAmount()));
                    row.add(ExcelUtil.formatComma(u.getQuarterAmount()));
                    row.add(ExcelUtil.formatComma(u.getTwoAmountIssue()));
                    row.add(ExcelUtil.formatComma(u.getTwoAmountYear()));
                    row.add(ExcelUtil.formatComma(u.getTwoAmountQuarter()));
                    row.add(ExcelUtil.formatComma(u.getAssetAmountYear()));
                    row.add(ExcelUtil.formatComma(u.getAssetAmountQuarter()));
                    row.add(ExcelUtil.formatComma(u.getAssetAmountIssue()));
                    row.add(u.getComment());
                    rows.add(row);
                } catch (Exception e) {
                    log.info("实际分配科目明细导出数据异常,主键{}", u.getPerformanceId());
                    log.info(e.getMessage());
                }
            });
            data.setRows(rows);
            try {
                ExportExcelUtils.exportExcel(response, name, data);
            } catch (Exception e) {
                log.error("异常原因:{}",e);
            }
        }
    }

private List<String> getSubYearTitleRowYear() {
        List<String> titles = new ArrayList<>();
        titles.add("");
        titles.add("");
        titles.add("");
        titles.add("");
        titles.add("");
        titles.add("");
        titles.add("");
        titles.add("年度应发合计");
        titles.add("一次分配合计");
        titles.add("二次分配合计");
        titles.add("资产对赌兑现");
        titles.add("");
        titles.add("");
        titles.add("");
        titles.add("拐点酬折算值");
        titles.add("公议系数");
        titles.add("(+)调节系数)");
        titles.add("兑现系数");
        titles.add("拐点酬应兑现");
        titles.add("其他一次科目汇总");
        titles.add("年度合计");
        titles.add("季度已兑现");
        titles.add("本期兑现合计");
        titles.add("年度合计");
        titles.add("季度已兑现");
        titles.add("年度合计");
        titles.add("季度已兑现");
        titles.add("本期兑现");
        titles.add("");
        return titles;
    }

private List<ExcelMergedRegion> fillYearMergedRegion() {
        List<ExcelMergedRegion> excelMergedRegionList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            excelMergedRegionList.add(new ExcelMergedRegion(0, 1, i, i));
        }
        excelMergedRegionList.add(new ExcelMergedRegion(0, 0, 7, 10));
        excelMergedRegionList.add(new ExcelMergedRegion(0, 1, 11, 11));
        excelMergedRegionList.add(new ExcelMergedRegion(0, 1, 12, 12));
        excelMergedRegionList.add(new ExcelMergedRegion(0, 1, 13, 13));
        excelMergedRegionList.add(new ExcelMergedRegion(0, 0, 14, 21));
        excelMergedRegionList.add(new ExcelMergedRegion(0, 0, 22, 24));
        excelMergedRegionList.add(new ExcelMergedRegion(0, 0, 25, 27));
        excelMergedRegionList.add(new ExcelMergedRegion(0, 1, 28, 28));
        return excelMergedRegionList;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值