java怎么将list写入excel

java怎么将list写入excel

Java将List写入Excel:Apache POI库、数据建模、文件流处理、单元格格式化

如果你需要将Java中的List数据写入Excel文件,可以使用Apache POI库。Apache POI是一个功能强大的Java库,专门用于操作Microsoft Office文档,包括Excel文件。接下来,我将详细描述如何使用Apache POI将List写入Excel文件的步骤。


一、准备工作:添加Apache POI依赖

要使用Apache POI库,首先需要在项目中添加相应的依赖。如果你使用的是Maven项目,可以在pom.xml文件中添加以下依赖:

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi</artifactId>

<version>5.0.0</version>

</dependency>

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi-ooxml</artifactId>

<version>5.0.0</version>

</dependency>

如果你不是使用Maven项目,可以下载相应的jar包并手动添加到项目的类路径中。

二、创建Excel文件和工作表

首先,我们需要创建一个Excel文件和一个工作表。Apache POI提供了XSSFWorkbookXSSFSheet类来完成这项工作:

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

import java.io.IOException;

public class ExcelWriter {

public static void main(String[] args) {

Workbook workbook = new XSSFWorkbook();

Sheet sheet = workbook.createSheet("Sheet1");

try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {

workbook.write(outputStream);

} catch (IOException e) {

e.printStackTrace();

}

}

}

三、将List数据写入Excel

假设我们有一个包含用户信息的List,每个用户有姓名、年龄和电子邮件地址。我们需要将这些信息写入Excel文件中。

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;

class User {

String name;

int age;

String email;

public User(String name, int age, String email) {

this.name = name;

this.age = age;

this.email = email;

}

}

public class ExcelWriter {

public static void main(String[] args) {

List<User> users = new ArrayList<>();

users.add(new User("Alice", 30, "alice@example.com"));

users.add(new User("Bob", 25, "bob@example.com"));

users.add(new User("Charlie", 35, "charlie@example.com"));

Workbook workbook = new XSSFWorkbook();

Sheet sheet = workbook.createSheet("Sheet1");

int rowCount = 0;

// Create header row

Row headerRow = sheet.createRow(rowCount++);

headerRow.createCell(0).setCellValue("Name");

headerRow.createCell(1).setCellValue("Age");

headerRow.createCell(2).setCellValue("Email");

for (User user : users) {

Row row = sheet.createRow(rowCount++);

row.createCell(0).setCellValue(user.name);

row.createCell(1).setCellValue(user.age);

row.createCell(2).setCellValue(user.email);

}

try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {

workbook.write(outputStream);

} catch (IOException e) {

e.printStackTrace();

}

}

}

四、处理单元格格式化

在许多情况下,简单地写入数据是不够的。我们可能还需要对单元格进行格式化,例如设置字体、颜色和对齐方式。Apache POI提供了丰富的API来实现这些功能。

设置字体和颜色

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

import java.io.IOException;

public class ExcelWriter {

public static void main(String[] args) {

Workbook workbook = new XSSFWorkbook();

Sheet sheet = workbook.createSheet("Sheet1");

// Create a font

Font headerFont = workbook.createFont();

headerFont.setBold(true);

headerFont.setFontHeightInPoints((short) 12);

headerFont.setColor(IndexedColors.RED.getIndex());

// Create a cell style

CellStyle headerCellStyle = workbook.createCellStyle();

headerCellStyle.setFont(headerFont);

// Create header row

Row headerRow = sheet.createRow(0);

String[] columns = {"Name", "Age", "Email"};

for (int i = 0; i < columns.length; i++) {

Cell cell = headerRow.createCell(i);

cell.setCellValue(columns[i]);

cell.setCellStyle(headerCellStyle);

}

try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {

workbook.write(outputStream);

} catch (IOException e) {

e.printStackTrace();

}

}

}

设置列宽和自动换行

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

import java.io.IOException;

public class ExcelWriter {

public static void main(String[] args) {

Workbook workbook = new XSSFWorkbook();

Sheet sheet = workbook.createSheet("Sheet1");

// Set column widths

sheet.setColumnWidth(0, 5000);

sheet.setColumnWidth(1, 3000);

sheet.setColumnWidth(2, 7000);

// Create a cell style for wrapping text

CellStyle wrapTextStyle = workbook.createCellStyle();

wrapTextStyle.setWrapText(true);

// Create a sample row with wrapped text

Row row = sheet.createRow(0);

Cell cell = row.createCell(0);

cell.setCellValue("This is a long text that should be wrapped in the cell.");

cell.setCellStyle(wrapTextStyle);

try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {

workbook.write(outputStream);

} catch (IOException e) {

e.printStackTrace();

}

}

}

五、处理日期和数字格式化

在实际应用中,处理日期和数字格式化是常见的需求。Apache POI提供了相关的API来处理这些格式化需求。

日期格式化

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Date;

public class ExcelWriter {

public static void main(String[] args) {

Workbook workbook = new XSSFWorkbook();

Sheet sheet = workbook.createSheet("Sheet1");

CreationHelper createHelper = workbook.getCreationHelper();

// Create a cell style for date formatting

CellStyle dateCellStyle = workbook.createCellStyle();

dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd-MM-yyyy"));

// Create a sample row with a date

Row row = sheet.createRow(0);

Cell cell = row.createCell(0);

cell.setCellValue(new Date());

cell.setCellStyle(dateCellStyle);

try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {

workbook.write(outputStream);

} catch (IOException e) {

e.printStackTrace();

}

}

}

数字格式化

import org.apache.poi.ss.usermodel.*;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

import java.io.IOException;

public class ExcelWriter {

public static void main(String[] args) {

Workbook workbook = new XSSFWorkbook();

Sheet sheet = workbook.createSheet("Sheet1");

// Create a cell style for number formatting

CellStyle numberCellStyle = workbook.createCellStyle();

numberCellStyle.setDataFormat(workbook.createDataFormat().getFormat("#,##0.00"));

// Create a sample row with a number

Row row = sheet.createRow(0);

Cell cell = row.createCell(0);

cell.setCellValue(12345.678);

cell.setCellStyle(numberCellStyle);

try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {

workbook.write(outputStream);

} catch (IOException e) {

e.printStackTrace();

}

}

}

六、写入复杂数据结构

在实际应用中,我们可能需要写入更复杂的数据结构,例如包含多个子列表的对象。在这种情况下,我们可以递归地处理这些数据结构。

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;

class Department {

String name;

List<Employee> employees;

public Department(String name, List<Employee> employees) {

this.name = name;

this.employees = employees;

}

}

class Employee {

String name;

int age;

String email;

public Employee(String name, int age, String email) {

this.name = name;

this.age = age;

this.email = email;

}

}

public class ExcelWriter {

public static void main(String[] args) {

List<Employee> employees1 = new ArrayList<>();

employees1.add(new Employee("Alice", 30, "alice@example.com"));

employees1.add(new Employee("Bob", 25, "bob@example.com"));

List<Employee> employees2 = new ArrayList<>();

employees2.add(new Employee("Charlie", 35, "charlie@example.com"));

employees2.add(new Employee("David", 40, "david@example.com"));

List<Department> departments = new ArrayList<>();

departments.add(new Department("HR", employees1));

departments.add(new Department("IT", employees2));

Workbook workbook = new XSSFWorkbook();

Sheet sheet = workbook.createSheet("Departments");

int rowCount = 0;

for (Department department : departments) {

Row deptRow = sheet.createRow(rowCount++);

deptRow.createCell(0).setCellValue(department.name);

for (Employee employee : department.employees) {

Row empRow = sheet.createRow(rowCount++);

empRow.createCell(1).setCellValue(employee.name);

empRow.createCell(2).setCellValue(employee.age);

empRow.createCell(3).setCellValue(employee.email);

}

}

try (FileOutputStream outputStream = new FileOutputStream("example.xlsx")) {

workbook.write(outputStream);

} catch (IOException e) {

e.printStackTrace();

}

}

}

七、总结

通过以上步骤,我们可以使用Apache POI库将Java中的List数据写入Excel文件中。Apache POI提供了丰富的API,可以处理各种数据格式、单元格格式化和复杂的数据结构。无论是简单的数据写入还是复杂的格式化需求,Apache POI都能够满足我们的需求。希望这篇文章能够帮助你更好地理解和使用Apache POI库。

相关问答FAQs:

1. 如何使用Java将List写入Excel表格?

您可以使用Apache POI库来实现将List写入Excel表格的功能。以下是一个简单的步骤:

  • 首先,确保您已经将Apache POI库添加到项目的依赖中。
  • 创建一个新的Workbook对象,如HSSFWorkbook或XSSFWorkbook,用于创建Excel文件。
  • 创建一个新的Sheet对象,并将其添加到Workbook中。
  • 遍历List中的每个对象,并将其数据写入Sheet中的相应单元格。
  • 最后,使用FileOutputStream将Workbook对象写入硬盘上的Excel文件。

2. 如何将List中的数据按照特定的格式写入Excel表格?

要按照特定的格式将List中的数据写入Excel表格,您可以使用CellStyle来设置单元格的格式。以下是一个示例代码:

  • 创建一个新的CellStyle对象,并设置所需的格式,例如背景颜色、字体样式等。
  • 遍历List中的每个对象,并将其数据写入Sheet中的相应单元格。
  • 在将数据写入单元格之前,使用setCellStyle方法将所需的CellStyle应用到单元格上。

3. 如何将List中的数据写入具有多个工作表的Excel文件中?

如果您想将List中的数据写入具有多个工作表的Excel文件中,您可以按照以下步骤操作:

  • 创建一个新的Workbook对象,如HSSFWorkbook或XSSFWorkbook。
  • 创建多个Sheet对象,并将其添加到Workbook中。
  • 遍历List中的每个对象,并根据需要将其数据写入不同的Sheet中。
  • 使用FileOutputStream将Workbook对象写入硬盘上的Excel文件。

希望以上解答能够帮助您将List数据成功写入Excel表格。如果您有任何其他问题,请随时提问!

文章包含AI辅助创作,作者:Edit2,如若转载,请注明出处:https://docs.pingcode.com/baike/4972040

(0)
Edit2Edit2
免费注册
电话联系

4008001024

微信咨询
微信咨询
返回顶部