您好,登录后才能下订单哦!
在现代企业级应用中,数据的导入导出是一个非常常见的需求。尤其是在处理大量数据时,Excel文件因其易用性和广泛的支持而成为首选格式。Spring Boot流行的Java框架,提供了强大的支持来简化开发过程。本文将详细介绍如何在Spring Boot项目中使用Apache POI库来实现Excel文件的导入和导出。
Apache POI是一个开源的Java库,用于处理Microsoft Office文档,包括Excel、Word和PowerPoint等。POI提供了丰富的API来创建、修改和读取这些文档。在本文中,我们将重点介绍如何使用POI来处理Excel文件。
在开始之前,我们需要确保我们的Spring Boot项目中已经包含了POI的依赖。可以通过Maven或Gradle来添加这些依赖。
在pom.xml
文件中添加以下依赖:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Apache POI for Excel -->
<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>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>5.1.1</version>
</dependency>
</dependencies>
在build.gradle
文件中添加以下依赖:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.apache.poi:poi:5.2.3'
implementation 'org.apache.poi:poi-ooxml:5.2.3'
implementation 'org.apache.poi:poi-ooxml-schemas:4.1.2'
implementation 'org.apache.xmlbeans:xmlbeans:5.1.1'
}
在添加了必要的依赖之后,我们可以创建一个简单的Spring Boot项目。假设我们已经有了一个基本的Spring Boot项目结构。
首先,我们需要定义一个简单的数据模型。假设我们要导出的数据是一个用户列表,每个用户有id
、name
和email
三个字段。
public class User {
private int id;
private String name;
private String email;
// 构造函数、getter和setter方法
}
接下来,我们创建一个服务类来处理Excel文件的导出。我们将使用POI的HSSFWorkbook
和XSSFWorkbook
来分别处理.xls
和.xlsx
格式的文件。
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
@Service
public class ExcelExportService {
public byte[] exportUsersToExcel(List<User> users, String fileType) throws IOException {
Workbook workbook;
if (fileType.equalsIgnoreCase("xls")) {
workbook = new HSSFWorkbook();
} else if (fileType.equalsIgnoreCase("xlsx")) {
workbook = new XSSFWorkbook();
} else {
throw new IllegalArgumentException("Unsupported file type: " + fileType);
}
Sheet sheet = workbook.createSheet("Users");
Row headerRow = sheet.createRow(0);
// 创建表头
String[] columns = {"ID", "Name", "Email"};
for (int i = 0; i < columns.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(columns[i]);
}
// 填充数据
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.getEmail());
}
// 调整列宽
for (int i = 0; i < columns.length; i++) {
sheet.autoSizeColumn(i);
}
// 将工作簿写入字节数组
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
workbook.close();
return outputStream.toByteArray();
}
}
最后,我们创建一个控制器来处理HTTP请求,并调用导出服务来生成Excel文件。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@RestController
public class ExcelExportController {
@Autowired
private ExcelExportService excelExportService;
@GetMapping("/export")
public ResponseEntity<ByteArrayResource> exportUsers(@RequestParam String fileType) throws IOException {
List<User> users = Arrays.asList(
new User(1, "John Doe", "john@example.com"),
new User(2, "Jane Doe", "jane@example.com")
);
byte[] excelBytes = excelExportService.exportUsersToExcel(users, fileType);
ByteArrayResource resource = new ByteArrayResource(excelBytes);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=users." + fileType)
.contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
.contentLength(excelBytes.length)
.body(resource);
}
}
启动Spring Boot应用程序,并访问http://localhost:8080/export?fileType=xlsx
,浏览器将自动下载一个名为users.xlsx
的Excel文件。
与导出类似,我们首先创建一个服务类来处理Excel文件的导入。
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Service
public class ExcelImportService {
public List<User> importUsersFromExcel(MultipartFile file) throws IOException {
List<User> users = new ArrayList<>();
InputStream inputStream = file.getInputStream();
Workbook workbook;
if (file.getOriginalFilename().endsWith("xls")) {
workbook = new HSSFWorkbook(inputStream);
} else if (file.getOriginalFilename().endsWith("xlsx")) {
workbook = new XSSFWorkbook(inputStream);
} else {
throw new IllegalArgumentException("Unsupported file type");
}
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
// 跳过表头
if (rowIterator.hasNext()) {
rowIterator.next();
}
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
User user = new User();
user.setId((int) row.getCell(0).getNumericCellValue());
user.setName(row.getCell(1).getStringCellValue());
user.setEmail(row.getCell(2).getStringCellValue());
users.add(user);
}
workbook.close();
inputStream.close();
return users;
}
}
接下来,我们创建一个控制器来处理文件上传请求,并调用导入服务来解析Excel文件。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
@RestController
public class ExcelImportController {
@Autowired
private ExcelImportService excelImportService;
@PostMapping("/import")
public List<User> importUsers(@RequestParam("file") MultipartFile file) throws IOException {
return excelImportService.importUsersFromExcel(file);
}
}
启动Spring Boot应用程序,并使用Postman或其他工具发送一个POST请求到http://localhost:8080/import
,上传一个Excel文件。服务器将解析文件并返回用户列表。
在本文中,我们详细介绍了如何在Spring Boot项目中使用Apache POI库来实现Excel文件的导入和导出。通过创建简单的数据模型、服务类和控制器,我们能够轻松地处理Excel文件的读写操作。希望本文能帮助你在实际项目中更好地处理Excel文件。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。