How to export Excel data using POI in Java?

With the POI library in Java, you can export Excel data. Below is an example code that can export data to an Excel file.

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 ExcelExporter {
    public static void main(String[] args) {
        // 创建数据列表
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("John", 25));
        personList.add(new Person("Jane", 30));
        personList.add(new Person("David", 35));

        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();

        // 创建表格
        Sheet sheet = workbook.createSheet("Person Data");

        // 创建表头
        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("Name");
        header.createCell(1).setCellValue("Age");

        // 创建数据行
        int rowNum = 1;
        for (Person person : personList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(person.getName());
            row.createCell(1).setCellValue(person.getAge());
        }

        // 调整列宽度
        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);

        // 保存文件
        try (FileOutputStream outputStream = new FileOutputStream("person_data.xlsx")) {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Excel文件导出成功!");
    }

    // 定义数据模型
    private static class Person {
        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }
    }
}

In this example, we utilized the XSSFWorkbook class to create a new workbook, followed by creating a table named “Person Data”. We used the createRow() method to create header and data rows, and set cell values using the setCellValue() method. Finally, we wrote the workbook to a file using FileOutputStream.

Please note that in this example the XSSFWorkbook class is used, which means the exported Excel file will be in .xlsx format. If you need to export as a .xls format file, you can use the HSSFWorkbook class to create the workbook.

bannerAds