根据自定义类属性导出Excel

根据自定义类属性导出Excel

之前的工作中遇到了导出Excel的功能需求,为了方便之后的工作使用,整理成一个Util

Jar包下载

https://download.csdn.net/download/qq_36757824/15451042

maven引用

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.13</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.13</version>
    </dependency>

先写一个注解,自定义实体类所需要的bean(Excel属性标题、位置等)


import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 自定义实体类所需要的bean(Excel属性标题、位置等)
 * @Author: jasen
 * @Date: 2020/11/20 13:40
 * @Description:
 */

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelColumn {
    /**
     * Excel标题
     *
     * @return
     * @author Lynch
     */
    String value() default "";

    /**
     * Excel从左往右排列位置
     *
     * @return
     * @author Lynch
     */
    int col() default 0;
}

在需要生成Excel的dao上标记注解

这里随便举个例子


import com.party.common.dto.ExcelColumn;

/**
 * @Author: jasen
 * @Date: 2020/11/20 13:53
 * @Description:
 */
public class ExportPartyFeeExcelByDeptDto {

    @ExcelColumn(value = "序号", col = 1)
    private long no;

    private String dpName;

    private long membersId;

    @ExcelColumn(value = "姓名", col = 2)
    private String name;

    private String leader;

    @ExcelColumn(value = "交费区间", col = 3)
    private String feeRange;

    @ExcelColumn(value = "交费标准(元)", col = 4)
    private Double standard;

    @ExcelColumn(value = "应交党费(元)", col = 5)
    private Double totalFee;

    @ExcelColumn(value = "备注", col = 6)
    private String remarks;

    public long getNo() {
        return no;
    }

    public void setNo(long no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

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

    public String getDpName() {
        return dpName;
    }

    public void setDpName(String dpName) {
        this.dpName = dpName;
    }

    public String getFeeRange() {
        return feeRange;
    }

    public void setFeeRange(String feeRange) {
        this.feeRange = feeRange;
    }

    public Double getStandard() {
        return standard;
    }

    public void setStandard(Double standard) {
        this.standard = standard;
    }

    public Double getTotalFee() {
        return totalFee;
    }

    public void setTotalFee(Double totalFee) {
        this.totalFee = totalFee;
    }

    public String getRemarks() {
        return remarks;
    }

    public void setRemarks(String remarks) {
        this.remarks = remarks;
    }

    public String getLeader() {
        return leader;
    }

    public void setLeader(String leader) {
        this.leader = leader;
    }

    public long getMembersId() {
        return membersId;
    }

    public void setMembersId(long membersId) {
        this.membersId = membersId;
    }
}

读写Excel

通过泛型来接收不同的实体类对象,使用的情况相对宽松一些
这里有一些很冗余的方法,就不一一封装了
写表格的地方做了一些个性化的处理,可以在之后的使用的时候处理一下


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletResponse;
import com.google.common.util.concurrent.AtomicDouble;
import com.party.common.dto.ExcelColumn;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
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.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
/**
 * @Author: jasen
 * @Date: 2020/11/20 13:40
 * @Description:
 */
public class ExcelUtils {

    private final static Logger log = LoggerFactory.getLogger(ExcelUtils.class);

    private final static String EXCEL2003 = "xls";
    private final static String EXCEL2007 = "xlsx";


    /**
     * 读取上传的表格
     * @param path
     * @param cls
     * @param file
     * @param <T>
     * @return
     */
    public static <T> List<T> readExcel(String path, Class<T> cls,MultipartFile file){

        String fileName = file.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            log.error("上传文件格式不正确");
        }
        List<T> dataList = new ArrayList<>();
        Workbook workbook = null;
        try {
            InputStream is = file.getInputStream();
            if (fileName.endsWith(EXCEL2007)) {
//                FileInputStream is = new FileInputStream(new File(path));
                workbook = new XSSFWorkbook(is);
            }
            if (fileName.endsWith(EXCEL2003)) {
//                FileInputStream is = new FileInputStream(new File(path));
                workbook = new HSSFWorkbook(is);
            }
            if (workbook != null) {
                //类映射  注解 value-->bean columns
                Map<String, List<Field>> classMap = new HashMap<>();
                List<Field> fields = Stream.of(cls.getDeclaredFields()).collect(Collectors.toList());
                fields.forEach(
                        field -> {
                            ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                            if (annotation != null) {
                                String value = annotation.value();
                                if (StringUtils.isBlank(value)) {
                                    return;//return起到的作用和continue是相同的 语法
                                }
                                if (!classMap.containsKey(value)) {
                                    classMap.put(value, new ArrayList<>());
                                }
                                field.setAccessible(true);
                                classMap.get(value).add(field);
                            }
                        }
                );
                //索引-->columns
                Map<Integer, List<Field>> reflectionMap = new HashMap<>(16);
                //默认读取第一个sheet
                Sheet sheet = workbook.getSheetAt(0);

                boolean firstRow = true;
                for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    //首行  提取注解
                    if (firstRow) {
                        for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
                            Cell cell = row.getCell(j);
                            String cellValue = getCellValue(cell);
                            if (classMap.containsKey(cellValue)) {
                                reflectionMap.put(j, classMap.get(cellValue));
                            }
                        }
                        firstRow = false;
                    } else {
                        //忽略空白行
                        if (row == null) {
                            continue;
                        }
                        try {
                            T t = cls.newInstance();
                            //判断是否为空白行
                            boolean allBlank = true;
                            for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
                                if (reflectionMap.containsKey(j)) {
                                    Cell cell = row.getCell(j);
                                    String cellValue = getCellValue(cell);
                                    if (StringUtils.isNotBlank(cellValue)) {
                                        allBlank = false;
                                    }
                                    List<Field> fieldList = reflectionMap.get(j);
                                    fieldList.forEach(
                                            x -> {
                                                try {
                                                    handleField(t, cellValue, x);
                                                } catch (Exception e) {
                                                    log.error(String.format("reflect field:%s value:%s exception!", x.getName(), cellValue), e);
                                                }
                                            }
                                    );
                                }
                            }
                            if (!allBlank) {
                                dataList.add(t);
                            } else {
                                log.warn(String.format("row:%s is blank ignore!", i));
                            }
                        } catch (Exception e) {
                            log.error(String.format("parse row:%s exception!", i), e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(String.format("parse excel exception!"), e);
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (Exception e) {
                    log.error(String.format("parse excel exception!"), e);
                }
            }
        }
        return dataList;
    }

    private static <T> void handleField(T t, String value, Field field) throws Exception {
        Class<?> type = field.getType();
        if (type == null || type == void.class || StringUtils.isBlank(value)) {
            return;
        }
        if (type == Object.class) {
            field.set(t, value);
            //数字类型
        } else if (type.getSuperclass() == null || type.getSuperclass() == Number.class) {
            if (type == int.class || type == Integer.class) {
                field.set(t, NumberUtils.toInt(value));
            } else if (type == long.class || type == Long.class) {
                field.set(t, NumberUtils.toLong(value));
            } else if (type == byte.class || type == Byte.class) {
                field.set(t, NumberUtils.toByte(value));
            } else if (type == short.class || type == Short.class) {
                field.set(t, NumberUtils.toShort(value));
            } else if (type == double.class || type == Double.class) {
                field.set(t, NumberUtils.toDouble(value));
            } else if (type == float.class || type == Float.class) {
                field.set(t, NumberUtils.toFloat(value));
            } else if (type == char.class || type == Character.class) {
                field.set(t, CharUtils.toChar(value));
            } else if (type == boolean.class) {
                field.set(t, BooleanUtils.toBoolean(value));
            } else if (type == BigDecimal.class) {
                field.set(t, new BigDecimal(value));
            }
        } else if (type == Boolean.class) {
            field.set(t, BooleanUtils.toBoolean(value));
        } else if (type == Date.class) {
            //
            field.set(t, value);
        } else if (type == String.class) {
            field.set(t, value);
        } else {
            Constructor<?> constructor = type.getConstructor(String.class);
            field.set(t, constructor.newInstance(value));
        }
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }

    }


    //设置不带边框的格式
    public static void setReportStyleWithoutBorder(Workbook workbook, Cell cell, short zyjz, short sxjz, short bw, short color, short fh, String fontName) {
        XSSFCellStyle cellStyle = (XSSFCellStyle) workbook.createCellStyle();
        cellStyle.setAlignment(zyjz);//左右居中
        cellStyle.setVerticalAlignment(sxjz);//上下居中
        Font font = workbook.createFont();
        font.setBoldweight(bw);
        font.setColor(color);
        font.setFontHeightInPoints(fh);
        font.setFontName(fontName);
        cellStyle.setFont(font);
        cell.setCellStyle(cellStyle);
    }

    //设置金钱的格式
    public static void setReportStyleWithFormat(Workbook workbook, Cell cell, short zyjz, short sxjz, short bw, short color, short fh, String fontName) {
        XSSFCellStyle cellStyle = (XSSFCellStyle) workbook.createCellStyle();
        DataFormat format = workbook.createDataFormat();
        cellStyle.setDataFormat(format.getFormat("¥\"\"#,##0.00;[red]\"\"#,##0.00"));
        cellStyle.setAlignment(zyjz);//左右居中
        cellStyle.setVerticalAlignment(sxjz);//上下居中
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN); // 下边框
        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);// 上边框
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);// 右边框
        Font font = workbook.createFont();
        font.setBoldweight(bw);
        font.setColor(color);
        font.setFontHeightInPoints(fh);
        font.setFontName(fontName);
        cellStyle.setFont(font);
        cell.setCellStyle(cellStyle);
    }


    //设置带边框的格式
    public static void setReportStyle(Workbook workbook, Cell cell, short zyjz, short sxjz, short bw, short color, short fh, String fontName) {
        XSSFCellStyle cellStyle = (XSSFCellStyle) workbook.createCellStyle();
        cellStyle.setAlignment(zyjz);//左右居中
        cellStyle.setVerticalAlignment(sxjz);//上下居中
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN); // 下边框
        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);// 上边框
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);// 右边框
//        cellStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(156, 195, 230)));//设置背景色
//        cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);//填充模式
        Font font = workbook.createFont();
        font.setBoldweight(bw);
        font.setColor(color);
        font.setFontHeightInPoints(fh);
        font.setFontName(fontName);
        cellStyle.setFont(font);
        cell.setCellStyle(cellStyle);
    }

    //设置带换行的格式
    public static void setReportStyleWithWrap(Workbook workbook, Cell cell, short zyjz, short sxjz, short bw, short color, short fh, String fontName) {
        XSSFCellStyle cellStyle = (XSSFCellStyle) workbook.createCellStyle();

        //自动换行
        cellStyle.setWrapText(true);

        cellStyle.setAlignment(zyjz);//左右居中
        cellStyle.setVerticalAlignment(sxjz);//上下居中
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN); // 下边框
        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);// 上边框
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);// 右边框
//        cellStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(156, 195, 230)));//设置背景色
//        cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);//填充模式
        Font font = workbook.createFont();
        font.setBoldweight(bw);
        font.setColor(color);
        font.setFontHeightInPoints(fh);
        font.setFontName(fontName);
        cellStyle.setFont(font);
        cell.setCellStyle(cellStyle);
    }

    //设置带下边框的格式
    public static void setReportStyleWithBottom(Workbook workbook, Cell cell, short zyjz, short sxjz, short bw, short color, short fh, String fontName) {
        XSSFCellStyle cellStyle = (XSSFCellStyle) workbook.createCellStyle();
        cellStyle.setAlignment(zyjz);//左右居中
        cellStyle.setVerticalAlignment(sxjz);//上下居中
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN); // 下边框
        Font font = workbook.createFont();
        font.setBoldweight(bw);
        font.setColor(color);
        font.setFontHeightInPoints(fh);
        font.setFontName(fontName);
        cellStyle.setFont(font);
        cell.setCellStyle(cellStyle);
    }

    //写表格
    public static <T> void writeExcel(HttpServletResponse response, List<T> dataList, Class<T> cls, String title, long size) {
        long t1 = System.currentTimeMillis();

        Field[] fields = cls.getDeclaredFields();
        List<Field> fieldList = Arrays.stream(fields)
                .filter(field -> {
                    ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                    if (annotation != null && annotation.col() > 0) {
                        field.setAccessible(true);
                        return true;
                    }
                    return false;
                }).sorted(Comparator.comparing(field -> {
                    int col = 0;
                    ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                    if (annotation != null) {
                        col = annotation.col();
                    }
                    return col;
                })).collect(Collectors.toList());

        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("Sheet1");
        AtomicInteger ai = new AtomicInteger();
        {
            //设置标题
            Row rowReportTitle = sheet.createRow(ai.getAndIncrement());
            rowReportTitle.setHeight((short) 500);
            Cell titleCell = rowReportTitle.createCell(0, Cell.CELL_TYPE_STRING);
            CellRangeAddress titleRegion = new CellRangeAddress(0, 0, 0, 6);
            setReportStyleWithoutBorder(wb, titleCell, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER,
                    HSSFFont.BOLDWEIGHT_BOLD, HSSFColor.BLACK.index, (short) 14,  "DengXian");
            sheet.addMergedRegion(titleRegion);
            Cell titleCell2 = rowReportTitle.getCell(0);
            titleCell2.setCellValue(title);
        }
        {
            //设置日期
            Row rowDate = sheet.createRow(ai.getAndIncrement());
            AtomicInteger aj = new AtomicInteger();
            //写入头部
            fieldList.forEach(field -> {
                rowDate.createCell(aj.getAndIncrement());
            });
            CellRangeAddress titleRegion = new CellRangeAddress(1, 1, 5, 6);
            Cell cell = rowDate.getCell(5);
            setReportStyleWithoutBorder(wb, cell, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER,
                    HSSFFont.BOLDWEIGHT_NORMAL, HSSFColor.BLACK.index, (short) 11,  "DengXian");
            sheet.addMergedRegion(titleRegion);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            cell.setCellValue(sdf.format(new Date()));
        }
        {
            Row row = sheet.createRow(ai.getAndIncrement());
            AtomicInteger aj = new AtomicInteger();
            //写入头部
            fieldList.forEach(field -> {
                ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                String columnName = "";
                if (annotation != null) {
                    columnName = annotation.value();
                }
                int i = aj.getAndIncrement();
                Cell cell = row.createCell(i);
                if ( i == 1) {
//                    sheet.setColumnWidth(i,  (int)((15 + 0.72) * 256));
//                    sheet.autoSizeColumn(1);
                    sheet.setColumnWidth(i, 256*12+184);
                    System.out.println(sheet.getColumnWidth(i)+"---------------------------"+columnName);
                }
                setReportStyle(wb, cell, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER,
                        HSSFFont.BOLDWEIGHT_BOLD, HSSFColor.BLACK.index, (short) 11,  "DengXian");
                cell.setCellValue(columnName);
            });
        }

        //写数据
        AtomicDouble total = new AtomicDouble();
        {
            if (!CollectionUtils.isEmpty(dataList)) {
                dataList.forEach(t -> {
                    Row row1 = sheet.createRow(ai.getAndIncrement());
                    AtomicInteger aj = new AtomicInteger();
                    fieldList.forEach(field -> {

                        Class<?> type = field.getType();
                        Object value = "";
                        try {
                            value = field.get(t);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        int i = aj.getAndIncrement();
                        Cell cell = row1.createCell(i);
                        if (i == 5 && !Objects.isNull(value)) {
                            total.addAndGet(Double.valueOf(value.toString()));
                        }
                        if (i == 3 || i == 2 ) {
                            sheet.setColumnWidth(i, 256 * 15 + 184);
//                            sheet.autoSizeColumn(1);
                            setReportStyle(wb, cell, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_CENTER,
                                    HSSFFont.BOLDWEIGHT_NORMAL, HSSFColor.BLACK.index, (short) 11, "DengXian");
                        } else if (i == 1) {
                            sheet.setColumnWidth(i, 256 * 12 + 184);
                            System.out.println(sheet.getColumnWidth(i)+"---------------------------"+value);
                            setReportStyleWithWrap(wb, cell, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_CENTER,
                                    HSSFFont.BOLDWEIGHT_NORMAL, HSSFColor.BLACK.index, (short) 11, "DengXian");
                        } else {
//                            sheet.autoSizeColumn(1);
                            setReportStyle(wb, cell, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER,
                                    HSSFFont.BOLDWEIGHT_NORMAL, HSSFColor.BLACK.index, (short) 11, "DengXian");
                        }
                        if (value != null) {
                            if (type == Date.class) {
                                cell.setCellValue(value.toString());
                            } else {
                                cell.setCellValue(value.toString());
                            }
                            cell.setCellValue(value.toString());
                        }
                    });
                });
            }
        }


        //合并单元格
        {
            AtomicInteger aj = new AtomicInteger();
            aj.getAndIncrement();
            aj.getAndIncrement();
            aj.getAndIncrement();
            if (!CollectionUtils.isEmpty(dataList)) {
                String dpName = "";
                int n1 = 0;
                for (Object t : dataList) {
                    //当前列 3开始
                    int m1 = aj.getAndIncrement();
                    Row row = sheet.getRow(m1);
                    Field field = fieldList.get(1);
                    String value = "";
                    try {
                        value = field.get(t).toString();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (!dpName.equals(value)) {
                        if (n1 > 0 ) {
                            //合并单元格
                            CellRangeAddress titleRegion = new CellRangeAddress(n1, m1-1, 1, 1);
                            sheet.addMergedRegion(titleRegion);
                            row.getCell(1).setCellValue(value);
                        }
                        n1 = m1;
                        dpName = value;
                    }
                }
            }
        }



        {
            int i = ai.getAndIncrement();
            Row rowDate = sheet.createRow(i);
            rowDate.setHeight((short) 425);
            AtomicInteger aj = new AtomicInteger();
            fieldList.forEach(field -> {
                int j = aj.getAndIncrement();
                Cell cell =  rowDate.createCell(j);
                setReportStyle(wb, cell, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER,
                        HSSFFont.BOLDWEIGHT_NORMAL, HSSFColor.BLACK.index, (short) 12,  "宋体");
            });
            //缴费人数
            {
                CellRangeAddress titleRegion = new CellRangeAddress(i, i, 0, 1);
                Cell cell = rowDate.getCell(0);
                setReportStyle(wb, cell, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER,
                        HSSFFont.BOLDWEIGHT_NORMAL, HSSFColor.BLACK.index, (short) 12,  "宋体");
                sheet.addMergedRegion(titleRegion);
                cell.setCellValue("交费人数");
            }
            //人数统计
            {
                Cell cell2 = rowDate.createCell(2);
                setReportStyle(wb, cell2, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER,
                        HSSFFont.BOLDWEIGHT_BOLD, HSSFColor.BLACK.index, (short) 12,  "DengXian");
                cell2.setCellValue(size);
            }
            //党费合计
            {
                Cell cell2 = rowDate.createCell(3);
                setReportStyle(wb, cell2, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER,
                        HSSFFont.BOLDWEIGHT_NORMAL, HSSFColor.BLACK.index, (short) 12,  "宋体");
                cell2.setCellValue("党费合计");
            }
            //党费合计数
            {
                CellRangeAddress titleRegion = new CellRangeAddress(i, i, 4, 6);
                sheet.addMergedRegion(titleRegion);
                Cell cell2 = rowDate.getCell(4);
                cell2.setCellValue(total.get());
                setReportStyleWithFormat(wb, cell2, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER,
                        HSSFFont.BOLDWEIGHT_BOLD, HSSFColor.BLACK.index, (short) 12,  "DengXian");
            }
        }
        {
            //倒数第二行
            Row rowDate = sheet.createRow(ai.getAndIncrement());
            AtomicInteger aj = new AtomicInteger();
            fieldList.forEach(field -> {
                int j = aj.getAndIncrement();
                Cell cell =  rowDate.createCell(j);
                setReportStyleWithBottom(wb, cell, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER,
                        HSSFFont.BOLDWEIGHT_NORMAL, HSSFColor.BLACK.index, (short) 12,  "DengXian");
            });
        }
        {
            //最后一行
            int i = ai.getAndIncrement();
            Row rowDate = sheet.createRow(i);
            rowDate.setHeight((short) 425);
            AtomicInteger aj = new AtomicInteger();
            fieldList.forEach(field -> {
                Cell cell = rowDate.createCell(aj.getAndIncrement());
                setReportStyleWithoutBorder(wb, cell, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_CENTER,
                        HSSFFont.BOLDWEIGHT_NORMAL, HSSFColor.BLACK.index, (short) 12,  "DengXian");
            });
            //经手人:
            {
                CellRangeAddress titleRegion = new CellRangeAddress(i, i, 1, 2);
                Cell cell = rowDate.getCell(1);
                setReportStyleWithoutBorder(wb, cell, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_CENTER,
                        HSSFFont.BOLDWEIGHT_NORMAL, HSSFColor.BLACK.index, (short) 12,  "DengXian");
                sheet.addMergedRegion(titleRegion);
                cell.setCellValue("经手人:");
            }
            //收款人:
            {
                CellRangeAddress titleRegion = new CellRangeAddress(i, i, 3, 4);
                Cell cell2 = rowDate.getCell(3);
                setReportStyleWithoutBorder(wb, cell2, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_CENTER,
                        HSSFFont.BOLDWEIGHT_NORMAL, HSSFColor.BLACK.index, (short) 12,  "DengXian");
                sheet.addMergedRegion(titleRegion);
                cell2.setCellValue("收款人:");
            }
        }
        //冻结窗格
        wb.getSheet("Sheet1").createFreezePane(0, 1, 0, 1);
        //浏览器下载excel
        buildExcelDocument(title+".xlsx",wb,response);
        //生成excel文件
//        buildExcelFile(".\\default.xlsx",wb);
        long t2 = System.currentTimeMillis();
        System.out.println(String.format("write over! cost:%sms", (t2 - t1)));
    }

    /**
     * 浏览器下载excel
     * @param fileName
     * @param wb
     * @param response
     */

    private static  void  buildExcelDocument(String fileName, Workbook wb,HttpServletResponse response){
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成excel文件
     * @param path 生成excel路径
     * @param wb
     */
    private static  void  buildExcelFile(String path, Workbook wb){

        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        try {
            wb.write(new FileOutputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值