spring boot 生成exel

Spring Boot生成Excel文件的详细教程

在本教程中,我们将介绍如何使用Spring Boot生成Excel文件。这种技能对于需要创建各种报告和数据表单的任何基于Web的应用程序都非常有用。我们将使用Apache POI库完成此任务,因为它对于生成Microsoft Office文件(如Excel)非常有效。让我们深入了解这个主题。

1. 引入依赖

首先,我们需要引入生成Excel文件所需的库。在`pom.xml`文件中添加以下两个依赖(如果使用Gradle,请自行转换):

```xml

org.apache.poi

poi

4.1.2

org.apache.poi

poi-ooxml

4.1.2

```

2. 创建Excel文件生成工具类

接下来,我们需要创建一个工具类,以完成实际生成Excel文件的工作。以下是`ExcelUtils`类的示例代码:

```java

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

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

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.util.List;

import java.util.Map;

public class ExcelUtils {

// 使用泛型的方式适用不同的数据类型

public static ByteArrayInputStream exportToExcel(String[] headers, List> data) throws IOException {

Workbook workbook = new XSSFWorkbook();

ByteArrayOutputStream out = new ByteArrayOutputStream();

CreationHelper createHelper = workbook.getCreationHelper();

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

Font headerFont = workbook.createFont();

headerFont.setBold(true);

CellStyle headerCellStyle = workbook.createCellStyle();

headerCellStyle.setFont(headerFont);

// 在Sheet中创建表头

Row headerRow = sheet.createRow(0);

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

Cell headerCell = headerRow.createCell(i);

headerCell.setCellValue(headers[i]);

headerCell.setCellStyle(headerCellStyle);

}

// 在Sheet中添加数据

int rowNum = 1;

for (Map rowData : data) {

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

int colNum = 0;

for (String header : headers) {

// 获取对应字段的数据值,并设置到单元格中

T value = rowData.get(header);

if (value != null) {

// 使用带String参数的setCellValue方法,可以避免数字、日期等类型的转换问题

row.createCell(colNum).setCellValue(value.toString());

}

colNum++;

}

}

// 自动调整列宽

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

sheet.autoSizeColumn(i);

}

// 将数据写入输出流,并关闭工作簿

workbook.write(out);

workbook.close();

return new ByteArrayInputStream(out.toByteArray());

}

}

```

3. 创建生成和下载Excel文件的Controller

现在我们已经创建了一个生成Excel文件的工具类,接下来我们需要创建一个Spring REST控制器,以实现将Excel文件作为响应返回。以下是一个示例`ExcelController`:

```java

import org.springframework.core.io.InputStreamResource;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;

import java.util.*;

@RestController

@RequestMapping("/api/excel")

public class ExcelController {

@GetMapping("/download")

public ResponseEntity downloadExcel() throws IOException {

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

// 假设我们有一个List存储用户信息

List> userList = new ArrayList<>();

userList.add(new HashMap() {

{

put("Name", "Tom");

put("Age", "25");

put("Email", "tom@example.com");

}

});

ByteArrayInputStream excelFile = ExcelUtils.exportToExcel(headers, userList);

return ResponseEntity.ok()

.header("Content-Disposition", "attachment; filename=users.xlsx")

.body(new InputStreamResource(excelFile));

}

}

```

现在,当我们访问`/api/excel/download`时,Spring Boot应用程序将生成一个包含示例数据的Excel文件,并并以附件形式提供下载。

总结:

在本教程中,我们介绍了如何使用Spring Boot和Apache POI库生成Excel文件。现在,您已经学会了如何创建一个基本的Excel文件生成器。您可以根据自己的需求来定制和扩展这些示例代码,例如,将数据从数据库中读取等。希望这篇文章对您有所帮助!