Java动态生成excel模板、和动态模板&数据导出

1、添加依赖

<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>4.0.0</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>4.0.0</version>
</dependency>
<dependency>
	<groupId>com.monitorjbl</groupId>
	<artifactId>xlsx-streamer</artifactId>
	<version>2.1.0</version>
</dependency>

2、导出excel工具类

package com.shucha.deveiface.biz.utils;

import com.monitorjbl.xlsx.StreamingReader;
import com.sdy.common.model.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ExcelUtil {
    /**
     * 数据导出成 Excel 数据格式
     *
     * @param headList 表头信息 (为null 或者 size() == 0 证明不存在)
     * @param dataList 数据信息
     * @return 结果数组
     */
    public static byte[] exportExcel(List<String> headList, List<Map<String, Object>> dataList, String xlsType) throws BizException {
        byte[] bytes = null;
        try (Workbook workbook = StringUtils.endsWithIgnoreCase(xlsType, "xlsx") ? new XSSFWorkbook() : new HSSFWorkbook();
             ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            int size = 65530;
//            int sheetCount = 0;
//            if (dataList.size() < size) {
//
//            }
            int sheetCount = dataList == null ? 0 : (dataList.size() < size ? 1 : (dataList.size() % size > 0 ? (dataList.size() / size) + 1 : dataList.size() / size));
            for (int i = 0; i < sheetCount; i++) {
                Sheet sheet = workbook.createSheet("sheet" + i);
                sheet.setDefaultColumnWidth(13);
                int rowIndex = 0;
                if (headList != null && headList.size() > 0) {
                    writerHeader(headList, sheet);
                    rowIndex++;
                }
                int end = dataList.size() > (size * (i + 1)) ? size : dataList.size();
                writerData(dataList.subList(i * size, end), headList, sheet, rowIndex);
            }
            workbook.write(os);
            bytes = os.toByteArray();
        } catch (Exception e) {
            throw new BizException("" + e);
        }
        return bytes;
    }

     // 写入本地文件  防止内存溢出
    public static void write(List<String> headList, List<Map<String, Object>> dataList, String xlsxPath, Integer size) throws BizException {
        File file = new File(xlsxPath);
//        if (file.exists()) {
//            file.delete();
//        }
        try (SXSSFWorkbook workbook = new SXSSFWorkbook();
             FileOutputStream outputStream = new FileOutputStream(file)) {
            int sheetCount = dataList == null ? 0 : (dataList.size() < size ? 1 : (dataList.size() % size > 0 ? (dataList.size() / size) + 1 : dataList.size() / size));
            for (int i = 0; i < sheetCount; i++) {
                Sheet sheet = workbook.createSheet(i + "");
                sheet.setDefaultColumnWidth(13);
                int rowIndex = 0;
                if (headList != null && headList.size() > 0) {
                    writerHeader(headList, sheet);
                    rowIndex++;
                }
                int end = dataList.size() > (size * (i + 1)) ? size : dataList.size();
                writerData(dataList.subList(i * size, end), headList, sheet, rowIndex);
            }
            workbook.write(outputStream);
        } catch (Exception e) {
            log.error("", e);
            throw new BizException("" + e);
        }
    }

    //读取本地文件 防止内存溢出
    public static List<Map<String, Object>> readExcel(File file, Integer size, Integer current) throws BizException {
        try (InputStream is = new FileInputStream(file);
             Workbook workbook = StreamingReader.builder()
                     .rowCacheSize(100)
                     .bufferSize(4096)
                     .open(is)) {
            List<String> headerList = new ArrayList<>();
            List<Map<String, Object>> dataList = new ArrayList<>();
            for (Sheet sheet : workbook) {
                log.info(sheet.getSheetName());
                int start = (current * size) + 1;
                int end = start + 10;
                int i = 0;
                for (Row row : sheet) {
                    if (i == 0) {
                        for (Cell cell : row) {
                            headerList.add(cell.getStringCellValue());
                        }
                    } else if (i > start && i <= end) {
                        Map<String, Object> map = new HashMap<>();
                        int j = 0;
                        for (Cell cell : row) {
                            map.put(headerList.get(j), cell.getStringCellValue());
                            j++;
                        }
                        dataList.add(map);
                    } else if (i > end) {
                        break;
                    }
                    i++;
                }
            }
            return dataList;
        } catch (Exception e) {
            log.error("", e);
            throw new BizException("" + e);
        }
    }

//    public static void writeExcel(List<String> headList, List<Map<String, Object>> dataList, String xlsxPath, Integer size) throws BizException {
//        File file = new File(xlsxPath);
//        if (file.exists()) {
//            file.delete();
//        }
//        try (SXSSFWorkbook workbook = new SXSSFWorkbook();
//             FileOutputStream outputStream = new FileOutputStream(file)) {
//            int sheetCount = dataList == null ? 0 : (dataList.size() < size ? 1 : (dataList.size() % size > 0 ? (dataList.size() / size) + 1 : dataList.size() / size));
//            for (int i = 0; i < sheetCount; i++) {
//                Sheet sheet = workbook.createSheet(i + "");
//                sheet.setDefaultColumnWidth(13);
//                int rowIndex = 0;
//                if (headList != null && headList.size() > 0) {
//                    writerHeader(headList, sheet);
//                    rowIndex++;
//                }
//                int end = dataList.size() > (size * (i + 1)) ? size : dataList.size();
//                writerData(dataList.subList(i * size, end), headList, sheet, rowIndex);
//            }
//            workbook.write(outputStream);
//        } catch (Exception e) {
//            throw new BizException("" + e);
//        }
//    }
//
//    public static void main(String[] args) throws BizException {
        List<String> headList = new ArrayList<>();
        List<Map<String, Object>> dataList = new ArrayList<>();
        headList.add("name");
        headList.add("value");
        for (int a = 0; a < 70000; a++) {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("name", "测试name" + a);
            map1.put("value", "测试value" + a);
            dataList.add(map1);
        }
        write(headList, dataList, "/opt/1111.xlsx", 500000);
        List<Map<String, Object>> maps = readExcel(new File("D:/opt/1111.xlsx"), 10, 50);
        maps.size();
//        Integer a = 0;
//        for (int i = 0; i < 10; i++) {
//            ExcelUtil excelUtil = new ExcelUtil();
//            excelUtil.test(a);
//            System.out.println(a);
//        }
//
//    }
//
//    public void test(Integer a) {
//        a = a + 1;
//    }

//    public static void main(String[] args) throws Exception {
//        String rootPath = "D:/";
//        createImage("检察院看板", new Font("宋体", Font.PLAIN, 30), Paths.get(rootPath, "b" + 4000 + ".png").toFile());
//    }

//    private static int[] getWidthAndHeight(String text, Font font) {
//        Rectangle2D r = font.getStringBounds(text, new FontRenderContext(
//                AffineTransform.getScaleInstance(1, 1), false, false));
//        int unitHeight = (int) Math.floor(r.getHeight());//
//        // 获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度
//        int width = (int) Math.round(r.getWidth()) + 1;
//        // 把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度
//        int height = unitHeight + 3;
//        System.out.println("width:" + width + ", height:" + height);
//        return new int[]{width, height};
        return new int[]{190, 28};
//    }
//
//    // 根据str,font的样式以及输出文件目录
//    public static void createImage(String text, Font font, File outFile)
//            throws Exception {
//        // 获取font的样式应用在str上的整个矩形
//        int[] arr = getWidthAndHeight(text, font);
//        int width = arr[0];
//        int height = arr[1];
//        // 创建图片
//        BufferedImage image = new BufferedImage(width, height,
//                BufferedImage.TYPE_INT_BGR);//创建图片画布
//        Graphics g = image.getGraphics();
//        g.setColor(Color.WHITE); // 先用白色填充整张图片,也就是背景
//        g.fillRect(0, 0, width, height);//画出矩形区域,以便于在矩形区域内写入文字
//        g.setColor(Color.black);// 再换成黑色,以便于写入文字
//        g.setFont(font);// 设置画笔字体
//        g.drawString(text, 0, font.getSize());// 画出一行字符串
//        g.drawString(text, 0, 2 * font.getSize());// 画出第二行字符串,注意y轴坐标需要变动
//        g.dispose();
//        ImageIO.write(image, "png", outFile);// 输出png图片
//    }


    public static byte[] exportExcelHead(List<String> headList, String xlsType) throws BizException {
        byte[] bytes = null;
        try (Workbook workbook = StringUtils.endsWithIgnoreCase(xlsType, "xlsx") ? new XSSFWorkbook() : new HSSFWorkbook();
             ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            Sheet sheet = workbook.createSheet(0 + "");
            sheet.setDefaultColumnWidth(13);
            if (headList != null && headList.size() > 0) {
                writerHeader(headList, sheet);
            }
            workbook.write(os);
            bytes = os.toByteArray();
        } catch (Exception e) {
            throw new BizException("" + e);
        }
        return bytes;
    }


    /**
     * 写表头
     *
     * @param headList 表头List
     * @param sheet    sheet
     */
    public static void writerHeader(List<String> headList, Sheet sheet) {
        Row row = sheet.createRow(0);
        row.setHeightInPoints(21);
        RichTextString text;
        for (int i = 0; i < headList.size(); i++) {
            Cell cell = row.createCell((short) i);
            text = new XSSFRichTextString(headList.get(i));
            cell.setCellValue(text.toString());
        }
    }

    /**
     * 写数据
     *
     * @param dataList 数据
     * @param headList 表头
     * @param sheet    sheel
     * @param rowIndex 单元格索引
     */
    public static void writerData(List<Map<String, Object>> dataList, List<String> headList, Sheet sheet, int rowIndex) {
        Row row;
        Cell cell;
        RichTextString text;
        for (int i = 0; i < dataList.size(); i++) {
            row = sheet.createRow(rowIndex + i);
            Map<String, Object> datas = dataList.get(i);
            for (int j = 0; j < headList.size(); j++) {
                cell = row.createCell(j);
                Object value = datas.get(headList.get(j));
                String data = value == null ? "" : String.valueOf(value);
                text = new XSSFRichTextString(data);
                cell.setCellValue(text);
            }
        }
    }


    public static Object getValue(Cell cell) {
        Object cellValue = "";
        if (cell != null) {
            //必须使用switch来获取单元格数据,否则会报错,除非确保execl所有单元格的数据类型一致
            switch (cell.getCellType()) {
                case BOOLEAN://获取布尔型数据
                    cellValue = cell.getBooleanCellValue();
                    break;
                case BLANK://获取空值
                    cellValue = cell.getBooleanCellValue();
                    break;
                case ERROR://获取错误单元格
                    cellValue = cell.getErrorCellValue();
                    break;
                case NUMERIC://获取数字类型的数据
                    cellValue = cell.getNumericCellValue();
                    break;
                case STRING://获取字符串
                    cellValue = cell.getStringCellValue();
                    break;
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }


}

3、测试调用生成excel文件

 @GetMapping("/template")
    @ApiOperation(value = "动态生成excel模板")
    public void templateDerive(HttpServletResponse response) throws BizException {
        List<String> paramList = new ArrayList<>();
        for (int i=0;i<5;i++) {
            paramList.add("标题名称"+ i);
        }
        try {
            byte[] bytes = ExcelUtil.exportExcelHead(paramList, "xlsx");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            String filename = "动态导出模板.xlsx";
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            response.getOutputStream().write(bytes);
        } catch (Exception e) {
            throw new BizException("模板文件生成失败!原因:" + e);
        }
    }

    @GetMapping("/templateExcelData")
    @ApiOperation(value = "导出模板和数据")
    public void templateExcelData(HttpServletResponse response) throws BizException {
        List<String> headList = new ArrayList<>();
//        for (int i=0;i<5;i++) {
//            headList.add("标题名称"+ i);
//        }
//        List<String> headList = new ArrayList<>();
        List<Map<String, Object>> dataList = new ArrayList<>();
        headList.add("name");
        headList.add("value");
       for (int a = 0; a < 50; a++) {
            Map<String, Object> map1 = new HashMap<>();
           map1.put("name", "测试name" + a);
           map1.put("value", "测试value" + a);
            dataList.add(map1);
      }
//        List<Map<String, Object>> dataLis = new ArrayList<>();
//        for (int j=0;j<5;j++){
//            Map<String, Object> map = new HashMap<>();
//            map.put("name","数据名称"+j);
//            dataLis.add(map);
//        }
        try {
            byte[] bytes = ExcelUtil.exportExcel(headList, dataList, "xlsx");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            String filename = "动态导出模板和数据.xlsx";
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            response.getOutputStream().write(bytes);
        } catch (Exception e) {
            throw new BizException("模板文件生成失败!原因:" + e);
        }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码奴生来只知道前进~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值