杰瑞科技汇

Java如何实现数据导出Excel表格?

Java 导出数据到 Excel 表格的几种方法

在 Java 中将数据导出到 Excel 表格有多种方式,以下是几种常用的方法:

Java如何实现数据导出Excel表格?-图1
(图片来源网络,侵删)

使用 Apache POI (推荐)

Apache POI 是最流行的 Java 操作 Office 文件的库。

Maven 依赖

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

示例代码

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ExcelExportExample {
    public static void main(String[] args) {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建工作表
        Sheet sheet = workbook.createSheet("用户数据");
        // 创建标题行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("ID");
        headerRow.createCell(1).setCellValue("姓名");
        headerRow.createCell(2).setCellValue("年龄");
        headerRow.createCell(3).setCellValue("邮箱");
        // 模拟数据
        List<User> users = new ArrayList<>();
        users.add(new User(1, "张三", 25, "zhangsan@example.com"));
        users.add(new User(2, "李四", 30, "lisi@example.com"));
        users.add(new User(3, "王五", 28, "wangwu@example.com"));
        // 填充数据
        int rowNum = 1;
        for (User user : users) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(user.getId());
            row.createCell(1).setCellValue(user.getName());
            row.createCell(2).setCellValue(user.getAge());
            row.createCell(3).setCellValue(user.getEmail());
        }
        // 自动调整列宽
        for (int i = 0; i < 4; i++) {
            sheet.autoSizeColumn(i);
        }
        // 写入文件
        try (FileOutputStream fileOut = new FileOutputStream("users.xlsx")) {
            workbook.write(fileOut);
            System.out.println("Excel文件导出成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    static class User {
        private int id;
        private String name;
        private int age;
        private String email;
        public User(int id, String name, int age, String email) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.email = email;
        }
        // getter方法
        public int getId() { return id; }
        public String getName() { return name; }
        public int getAge() { return age; }
        public String getEmail() { return email; }
    }
}

使用 EasyExcel (阿里开源)

EasyExcel 是阿里巴巴开源的 Excel 处理框架,性能更好,内存占用更小。

Maven 依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.1.1</version>
</dependency>

示例代码

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class EasyExcelExportExample {
    public static void main(String[] args) {
        // 设置表头样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 11);
        headWriteCellStyle.setWriteFont(headWriteFont);
        // 设置内容样式
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontHeightInPoints((short) 10);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        // 构建样式策略
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = 
            new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        // 准备数据
        List<User> users = new ArrayList<>();
        users.add(new User(1, "张三", 25, new Date()));
        users.add(new User(2, "李四", 30, new Date()));
        users.add(new User(3, "王五", 28, new Date()));
        // 写入Excel
        String fileName = "users_easy.xlsx";
        EasyExcel.write(fileName, User.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("用户数据")
                .doWrite(users);
        System.out.println("Excel文件导出成功!");
    }
    // 使用注解定义Excel映射
    public static class User {
        @ExcelProperty("ID")
        private int id;
        @ExcelProperty("姓名")
        private String name;
        @ExcelProperty("年龄")
        private int age;
        @ExcelProperty("出生日期")
        private Date birthDate;
        public User(int id, String name, int age, Date birthDate) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.birthDate = birthDate;
        }
        // getter和setter方法
        public int getId() { return id; }
        public void setId(int id) { this.id = id; }
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public int getAge() { return age; }
        public void setAge(int age) { this.age = age; }
        public Date getBirthDate() { return birthDate; }
        public void setBirthDate(Date birthDate) { this.birthDate = birthDate; }
    }
}

使用 JXL (较简单)

JXL 是一个简单的 Java Excel 操作库,但已不再更新。

Maven 依赖

<dependency>
    <groupId>net.sourceforge.jexcelapi</groupId>
    <artifactId>jxl</artifactId>
    <version>2.6.12</version>
</dependency>

示例代码

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class JxlExportExample {
    public static void main(String[] args) {
        String fileName = "users_jxl.xls";
        List<User> users = new ArrayList<>();
        users.add(new User(1, "张三", 25));
        users.add(new User(2, "李四", 30));
        users.add(new User(3, "王五", 28));
        try (WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName))) {
            WritableSheet sheet = workbook.createSheet("用户数据", 0);
            // 添加标题
            sheet.addCell(new Label(0, 0, "ID"));
            sheet.addCell(new Label(1, 0, "姓名"));
            sheet.addCell(new Label(2, 0, "年龄"));
            // 添加数据
            int rowNum = 1;
            for (User user : users) {
                sheet.addCell(new Label(0, rowNum, String.valueOf(user.getId())));
                sheet.addCell(new Label(1, rowNum, user.getName()));
                sheet.addCell(new Label(2, rowNum, String.valueOf(user.getAge())));
                rowNum++;
            }
            workbook.write();
            System.out.println("Excel文件导出成功!");
        } catch (IOException | WriteException e) {
            e.printStackTrace();
        }
    }
    static class User {
        private int id;
        private String name;
        private int age;
        public User(int id, String name, int age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }
        // getter方法
        public int getId() { return id; }
        public String getName() { return name; }
        public int getAge() { return age; }
    }
}

在 Web 应用中导出 (Spring Boot 示例)

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@RestController
public class ExcelExportController {
    @GetMapping("/export/excel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=users.xlsx");
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("用户数据");
        // 创建标题行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("ID");
        headerRow.createCell(1).setCellValue("姓名");
        headerRow.createCell(2).setCellValue("年龄");
        // 模拟数据
        List<User> users = new ArrayList<>();
        users.add(new User(1, "张三", 25));
        users.add(new User(2, "李四", 30));
        users.add(new User(3, "王五", 28));
        // 填充数据
        int rowNum = 1;
        for (User user : users) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(user.getId());
            row.createCell(1).setCellValue(user.getName());
            row.createCell(2).setCellValue(user.getAge());
        }
        // 写入响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }
    static class User {
        private int id;
        private String name;
        private int age;
        public User(int id, String name, int age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }
        // getter方法
        public int getId() { return id; }
        public String getName() { return name; }
        public int getAge() { return age; }
    }
}

选择建议

  1. Apache POI:功能最全面,支持所有 Excel 格式,适合复杂需求
  2. EasyExcel:性能更好,内存占用少,适合大数据量导出
  3. JXL:简单易用,但功能有限且已不更新,适合简单需求
  4. Web 导出:使用 HttpServletResponse 直接输出到浏览器

根据你的具体需求选择合适的方法,对于大多数现代 Java 项目,推荐使用 Apache POI 或 EasyExcel。

Java如何实现数据导出Excel表格?-图2
(图片来源网络,侵删)
Java如何实现数据导出Excel表格?-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇