跳到主要内容
极客日志极客日志
首页博客AI提示词GitHub精选代理工具
搜索
|注册
博客列表
Javajava

Java 使用 Apache POI 导出 Excel 文件

Apache POI 是 Java 处理 Excel 的常用库。通过 Maven 引入 poi 依赖,定义 LogInfo 数据模型,编写 Excels 工具类生成 HSSFWorkbook 工作簿,设置样式与合并单元格,将日志列表写入字节数组并保存为 xls 文件。测试代码演示了如何调用工具类导出包含索引、时间及信息的日志数据至本地路径。

王初壹发布于 2025/1/17更新于 2026/4/251 浏览
Java 使用 Apache POI 导出 Excel 文件

1. Excel 依赖包 POI

1.1 Maven 配置

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.7</version>
</dependency>

1.2 资源下载

Apache POI 官方下载

2. Java 代码示例

2.1 Excel 工具类

package com.mk.util;
import com.mk.bean.LogInfo;
import org.apache.poi.hssf.usermodel.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.ss.util.CellRangeAddress;

public class Excels {
    public static byte[] export(String sheetName, String title, List<LogInfo> list, int start, int end) {
        if (list == null || start > end) {
            return null;
        }
        HSSFWorkbook workbook = new HSSFWorkbook();
        initWorkbook(workbook, sheetName, title, list, start, end);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            workbook.write(os);
            byte[] bytes = os.toByteArray();
            return bytes;
        } catch (IOException ex) {
            Logger.getLogger(Excels.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                os.close();
            } catch (IOException ex) {
                Logger.getLogger(Excels.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return null;
    }
    private static final int MAX_ROWS = 65535;
    private static void initWorkbook(HSSFWorkbook workbook, String sheetName, String title, List<LogInfo> list, int start, int end) {
        assert end - start <= MAX_ROWS - 2;
        HSSFSheet sheet = workbook.createSheet(sheetName);
        initTitle(workbook, sheet, title, 0, 16, 800, 0, 0, 0, 2);
        HSSFCellStyle attrCellStyle = createStyle(workbook, 10, true, HSSFFont.BOLDWEIGHT_BOLD);
        HSSFCellStyle defaultCellStyle = createStyle(workbook, 10, true, HSSFFont.BOLDWEIGHT_NORMAL);
        HSSFRow attrRow = sheet.createRow(1);
        final int baseFont = 10;
        sheet.setColumnWidth(0, baseFont * 400);
        sheet.setColumnWidth(1, baseFont * 800);
        sheet.setColumnWidth(2, baseFont * 1200);
        HSSFCell cell = attrRow.createCell(0);
        cell.setCellValue("索引");
        cell.setCellStyle(attrCellStyle);
        cell = attrRow.createCell(1);
        cell.setCellValue("时间");
        cell.setCellStyle(attrCellStyle);
        cell = attrRow.createCell(2);
        cell.setCellValue("信息");
        cell.setCellStyle(attrCellStyle);
        DateFormat dateFomater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 2; start < end; i++) {
            LogInfo logInfo = list.get(start++);
            HSSFRow row = sheet.createRow(i);
            cell = row.createCell(0);
            cell.setCellValue(logInfo.getIndex());
            cell.setCellStyle(defaultCellStyle);
            cell = row.createCell(1);
            cell.setCellValue(dateFomater.format(logInfo.getTime()));
            cell.setCellStyle(defaultCellStyle);
            cell = row.createCell(2);
            cell.setCellValue(logInfo.getInfo());
            cell.setCellStyle(defaultCellStyle);
        }
    }
    private static void initTitle(HSSFWorkbook workbook, HSSFSheet sheet, String title, int rowIndex, int fontSize, int height, int firstRow, int lastRow, int firstCol, int lastCol) {
        HSSFCellStyle titleCellStyle = createStyle(workbook, fontSize, true, HSSFFont.BOLDWEIGHT_BOLD);
        HSSFRow titleRow = sheet.createRow(0);
        titleRow.setHeight((short) height);
        HSSFCell titleCell = titleRow.createCell(rowIndex);
        titleCell.setCellValue(title);
        titleCell.setCellStyle(titleCellStyle);
        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
    }
    private static HSSFCellStyle createStyle(HSSFWorkbook workbook, int fontSize, boolean wrapText, short boldweight) {
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) fontSize);
        font.setBoldweight(boldweight);
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyle.setWrapText(wrapText);
        cellStyle.setFont(font);
        return cellStyle;
    }
}

2.2 数据模型

package com.mk.bean;
import java.util.Date;

public class LogInfo {
    private int index;
    private Date time;
    private String info;

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public Date getTime() {
        return time;
    }

    public void setTime(Date time) {
        this.time = time;
    }

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }
}

2.3 测试代码

package com.mk.testmaven;
import com.mk.bean.LogInfo;
import com.mk.util.Excels;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<LogInfo> list = new ArrayList<>();
        LogInfo logInfo = new LogInfo();
        logInfo.setIndex(0);
        logInfo.setInfo("你好");
        logInfo.setTime(new Date(2018, 9, 12));
        list.add(logInfo);
        logInfo = new LogInfo();
        logInfo.setIndex(1);
        logInfo.setInfo("问你");
        logInfo.setTime(new Date(2018, 9, 15));
        list.add(logInfo);
        logInfo = new LogInfo();
        logInfo.setIndex(2);
        logInfo.setInfo("世界");
        logInfo.setTime(new Date(2018, 9, 17));
        list.add(logInfo);
        byte[] bs = Excels.export("1", "日志", list, 0, list.size());
        try (FileOutputStream outputStream = new FileOutputStream("D:/log.xls")) {
            outputStream.write(bs);
            outputStream.flush();
        } catch (Exception e) {
        }
    }
}

目录

  1. 1. Excel 依赖包 POI
  2. 1.1 Maven 配置
  3. 1.2 资源下载
  4. 2. Java 代码示例
  5. 2.1 Excel 工具类
  6. 2.2 数据模型
  7. 2.3 测试代码
  • 💰 8折买阿里云服务器限时8折了解详情
  • 💰 8折买阿里云服务器限时8折购买
  • 🦞 5分钟部署阿里云小龙虾了解详情
  • 🤖 一键搭建Deepseek满血版了解详情
  • 一键打造专属AI 智能体了解详情
极客日志微信公众号二维码

微信扫一扫,关注极客日志

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog

更多推荐文章

查看全部
  • Python 调用通义千问 Qwen2.5 模型完整流程
  • DIAMOND 基因序列快速比对工具使用及超算集群并行计算指南
  • Java 并发性能优化:如何避免伪共享
  • Linux 下 Java JAR 包后台运行与端口检查实战
  • 测试驱动开发(TDD)核心流程与 Java 实战
  • PyTorch JIT 与 TorchScript:实测推理性能提升 50%
  • MySQL Range 分区实战:解决千万级数据查询性能瓶颈
  • Linux 基础命令与文件操作实战笔记
  • 图对比学习综述(一):对比范式与优化目标
  • Shell 脚本中 date 命令常用技巧与实战
  • SpringBoot 集成 MyBatis-Plus Dynamic-Datasource 实现主从多数据源
  • 串的数据结构定义与 C 语言堆分配存储实现
  • PHP 接口开发:XML 数据的生成与解析实战
  • Office 区域限制导致 Copilot 无法使用的解决方案
  • LLaMA-Factory 大模型微调技术背景与流程
  • 汇川机器人软件 RobotLab 常规操作
  • 小米智能家居 Miloco 分离式部署实战
  • Python dotenv 库 load_dotenv() 使用指南:安全管理环境变量
  • 鸿蒙系统卓易通安装应用的通知异常分析
  • Java 中间件:Dubbo 服务降级(Mock 机制)

相关免费在线工具

  • Keycode 信息

    查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online

  • Escape 与 Native 编解码

    JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online

  • JavaScript / HTML 格式化

    使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online

  • JavaScript 压缩与混淆

    Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online