21xrx.com
2025-03-24 08:05:40 Monday
文章检索 我的文章 写文章
Java实现Excel数据导出
2023-06-16 16:10:24 深夜i     10     0
Java 导出 Excel

在实际的开发中,我们经常需要将数据导出到Excel中,Java提供了各种方式来实现这个目的。下面我们介绍两种方法:一种是利用Apache POI库,另一种是使用easyPOI工具类。

1.使用Apache POI库

Apache POI是一个 Java API,提供了对 Microsoft Office 的读写功能。通过POI库,我们可以使用Java获取Excel文档的内容,也可以使用Java向Excel文档写入内容。

下面是一个简单的POI示例代码:

import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelExportUtil {
  public static void main(String[] args) throws IOException {
    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("Sheet1");
    Row row = sheet.createRow(0);
    Cell cell = row.createCell(0);
    cell.setCellValue("Hello World!");
    FileOutputStream outputStream = new FileOutputStream("output.xlsx");
    workbook.write(outputStream);
    outputStream.close();
  }
}

以上代码新建了一个Excel工作簿和一个名为“Sheet1”的工作表,然后在第一行第一列填写了“Hello World!”,最后将结果输出到一个名为“output.xlsx”的文件中。

2.使用easyPOI工具类

在构建一个复杂的数据结构时,easyPOI工具类比起手动创建POI对象更加方便。easyPOI提供了各种各样的注解来快速生成Excel文档,并且支持复杂数据结构的导出。

下面是一个使用easyPOI工具类的示例代码:

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import cn.afterturn.easypoi.excel.annotation.ExcelIgnore;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
public class UserInfo {
  @Excel(name = "姓名", width = 15)
  private String name;
  @Excel(name = "年龄", width = 15)
  private Integer age;
  @ExcelCollection(name = "学生列表")
  private List
  students = new ArrayList<>();
 
  @Data
  public static class Student {
    @Excel(name = "学号", width = 15)
    private String id;
    @Excel(name = "姓名", width = 15)
    private String name;
    @ExcelIgnore
    private Integer age;
  }
}

以上代码定义了一个UserInfo类,其中包含了一个名为“学生列表”的List对象,这个对象中又包含了Student子类。使用@Excel注解可以快速将类中的属性导出到Excel中。

三个

  
  

评论区