在現代企業級應用中,數據的導入導出是一個非常常見的需求。尤其是在處理大量數據時,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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。