easyExcel使用总结

easyExcel使用总结

1、数据库查询出来的数据写入excel文件中,不使用实体类

package com.fgi.importdata.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.fgi.importdata.service.impl.ModelLogServiceImpl;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;


public class ExcelUtils {
    private static ExcelUtils instance = new ExcelUtils();

    private ModelLogServiceImpl modelLogService;

    public ExcelUtils(ModelLogServiceImpl modelLogService) {
        this.modelLogService = modelLogService;
    }

    private ExcelUtils() {
    }

    public static ExcelUtils getInstance() {
        return instance;
    }

    /**
     * 将 List<Map<String,Object>> 类型的数据导出为 Excel
     * 默认 Excel 文件的输出路径为 项目根目录下
     * 文件名为 filename + 时间戳 + .xlsx
     *
     * @param mapList  数据源(通常为数据库查询数据)
     * @param filename 文件名前缀, 实际文件名后会加上日期
     * @param title    表格首行标题
     * @return 文件输出路径
     */
    public String createExcel(List<Map<String, Object>> mapList, String filename, String title) {
        //获取数据源的 key, 用于获取列数及设置标题
        Map<String, Object> map = mapList.get(0);
        Set<String> stringSet = map.keySet();
        ArrayList<String> headList = new ArrayList<>(stringSet);

        //定义一个新的工作簿
        XSSFWorkbook wb = new XSSFWorkbook();
        //创建一个Sheet页
        XSSFSheet sheet = wb.createSheet(title);
        //设置行高
        sheet.setDefaultRowHeight((short) (2 * 256));
        //为有数据的每列设置列宽
        for (int i = 0; i < headList.size(); i++) {
            sheet.setColumnWidth(i, 8000);
        }
        //设置单元格字体样式
        XSSFFont font = wb.createFont();
        font.setFontName("等线");
        font.setFontHeightInPoints((short) 16);

        //在sheet里创建第一行,并设置单元格内容为 title (标题)
        XSSFRow titleRow = sheet.createRow(0);
        XSSFCell titleCell = titleRow.createCell(0);
        titleCell.setCellValue(title);
        //合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headList.size() - 1));
        // 创建单元格文字居中样式并设置标题单元格居中
        XSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        titleCell.setCellStyle(cellStyle);

        //获得表格第二行
        XSSFRow row = sheet.createRow(1);
        //根据数据源信息给第二行每一列设置标题
        for (int i = 0; i < headList.size(); i++) {
            XSSFCell cell = row.createCell(i);
            cell.setCellValue(headList.get(i));
        }

        XSSFRow rows;
        XSSFCell cells;
        //循环拿到的数据给所有行每一列设置对应的值
        for (int i = 0; i < mapList.size(); i++) {
            //在这个sheet页里创建一行
            rows = sheet.createRow(i + 2);
            //给该行数据赋值
            for (int j = 0; j < headList.size(); j++) {
                String value = mapList.get(i).get(headList.get(j)).toString();
                cells = rows.createCell(j);
                cells.setCellValue(value);
            }
        }

        // 使用项目根目录, 文件名加上时间戳
//        String path = System.getProperty("user.dir") + "\\src\\main\\resources\\file\\" + filename;
//        System.out.println("Excel文件输出路径: " + path);
        try {
            File file = new File("D:\\test\\file\\" + filename);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            wb.write(fileOutputStream);
            wb.close();
            fileOutputStream.close();
            System.out.println("生成成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filename;
    }

   

    public static void main(String[] args) {
        System.out.println("数据加载...");
        List<Map<String, Object>> mapArrayList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("姓名", i);
            map.put("年龄", i);
            map.put("性别", i);
            mapArrayList.add(map);
        }
        System.out.println("数据加载完成...");

        ExcelUtils.getInstance().createExcel(mapArrayList, "文件名", "测试数据");
    }
}

2、同源写入多个sheet中

 /**
     * 同源写入多个sheet中
     *
     * @param num 单个sheet行数
     * @param filePath 文件路径
     * @param clazz 类型
     * @param dataList 数据集合
     * @param <T>
     * @param <E>
     * @return
     * @throws IOException
     */
    public <T, E> String createExcel02(Integer num, String filePath, Class<T> clazz, List<E> dataList) {
        // 创建一个EasyExcel写入器
        ExcelWriter excelWriter = EasyExcel.write(filePath, clazz).build();
        // 从数据库中查询出要写入Excel的数据
        int sheetNum = (dataList.size() + (num - 1)) / num; // 计算sheet数量
        for (int i = 0; i < sheetNum; i++) {
            // 创建一个表单
            WriteSheet sheet = EasyExcel.writerSheet("sheet" + (i + 1)).build();
            // 计算每个sheet中的数据范围
            int startIndex = i * num;
            int endIndex = Math.min(startIndex + num, dataList.size());
            // 获取每个sheet中要写入的数据
            List<E> sheetData = dataList.subList(startIndex, endIndex);
            // 使用ExcelWriter写入数据
            excelWriter.write(sheetData, sheet);
        }
        // 关闭ExcelWriter
        excelWriter.finish();
        return filePath;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

江南_烟雨.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值