SpringMVC框架使用 Apache POI實現(xiàn)導(dǎo)出Excel
在企業(yè)級應(yīng)用開發(fā)中,數(shù)據(jù)的導(dǎo)入導(dǎo)出是一項常見的需求。Excel 作為最常用的數(shù)據(jù)處理工具之一,經(jīng)常被用來存儲和展示數(shù)據(jù)。本文將介紹如何在 SpringMVC 框架中使用 Apache POI 庫來實現(xiàn) Excel 文件的導(dǎo)出功能。
1.引入
1.1 添加依賴
首先,在項目的 ??pom.xml?? 文件中添加 Apache POI 的依賴:
<dependencies>
<!-- 其他依賴 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
</dependencies>
1.2 創(chuàng)建 Maven 項目
確保你的項目是一個 Maven 項目,并且已經(jīng)配置好了 SpringMVC 框架。
2. 創(chuàng)建控制器
接下來,我們創(chuàng)建一個控制器來處理導(dǎo)出 Excel 的請求。
package com.example.controller;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
@Controller
@RequestMapping("/excel")
public class ExcelController {
@GetMapping("/export")
public void exportExcel(HttpServletResponse response) throws IOException {
// 設(shè)置響應(yīng)頭
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("用戶信息", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
// 創(chuàng)建工作簿
Workbook workbook = new XSSFWorkbook();
// 創(chuàng)建工作表
Sheet sheet = workbook.createSheet("用戶信息");
// 創(chuàng)建標(biāo)題行
Row headerRow = sheet.createRow(0);
List<String> headers = Arrays.asList("ID", "姓名", "年齡", "郵箱");
for (int i = 0; i < headers.size(); i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers.get(i));
}
// 填充數(shù)據(jù)
List<User> users = getUsers();
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.getAge());
row.createCell(3).setCellValue(user.getEmail());
}
// 輸出 Excel 文件
workbook.write(response.getOutputStream());
workbook.close();
}
private List<User> getUsers() {
return Arrays.asList(
new User(1, "張三", 28, "zhangsan@example.com"),
new User(2, "李四", 30, "lisi@example.com"),
new User(3, "王五", 25, "wangwu@example.com")
);
}
}
class User {
private int id;
private String name;
private int age;
private String email;
public User(int id, String name, int age, String email) {
this.id = id;
this.name = name;
this.age = age;
this.email = email;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
}3. 配置 SpringMVC
確保你的 ??web.xml?? 或 ??SpringMVC?? 配置文件中已經(jīng)配置了 DispatcherServlet 和相關(guān)組件。
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
4. 測試導(dǎo)出功能
啟動你的應(yīng)用服務(wù)器,訪問以下 URL 來測試導(dǎo)出功能:
http://localhost:8080/your-app/excel/export
如果一切正常,你應(yīng)該會看到瀏覽器提示你下載一個名為“用戶信息.xlsx”的 Excel 文件。
5. 方法補充
下面是一個使用 Spring MVC 和 Apache POI 導(dǎo)出 Excel 文件的示例代碼。這個示例假設(shè)你已經(jīng)有一個 Spring Boot 項目,并且需要從數(shù)據(jù)庫中獲取數(shù)據(jù)并將其導(dǎo)出為 Excel 文件。
1. 添加依賴
首先,在你的 `pom.xml` 文件中添加 Apache POI 的依賴:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
2. 創(chuàng)建實體類
假設(shè)你有一個 ??User?? 實體類,表示用戶信息:
public class User {
private Long id;
private String name;
private String email;
private int age;
// Getters and Setters
}
3. 創(chuàng)建服務(wù)類
創(chuàng)建一個服務(wù)類來處理數(shù)據(jù)的獲取和 Excel 文件的生成:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
@Service
public class UserService {
// 假設(shè)這里有一個方法從數(shù)據(jù)庫中獲取用戶列表
public List<User> getUsers() {
// 這里可以調(diào)用 DAO 或 Repository 來獲取數(shù)據(jù)
return List.of(
new User(1L, "張三", "zhangsan@example.com", 28),
new User(2L, "李四", "lisi@example.com", 30)
);
}
public ByteArrayInputStream exportUsersToExcel() throws IOException {
List<User> users = getUsers();
try (Workbook workbook = new XSSFWorkbook(); ByteArrayOutputStream out = new ByteArrayOutputStream()) {
Sheet sheet = workbook.createSheet("Users");
// 創(chuàng)建表頭
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("ID");
headerRow.createCell(1).setCellValue("Name");
headerRow.createCell(2).setCellValue("Email");
headerRow.createCell(3).setCellValue("Age");
// 填充數(shù)據(jù)
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());
row.createCell(3).setCellValue(user.getAge());
}
workbook.write(out);
return new ByteArrayInputStream(out.toByteArray());
}
}
}4. 創(chuàng)建控制器
創(chuàng)建一個控制器來處理 HTTP 請求并返回 Excel 文件:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
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.io.IOException;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/export-excel")
public ResponseEntity<ByteArrayResource> exportUsersToExcel() throws IOException {
ByteArrayInputStream bis = userService.exportUsersToExcel();
// 設(shè)置響應(yīng)頭
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename=users.xlsx");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(bis.available())
.body(new ByteArrayResource(bis.readAllBytes()));
}
}5. 配置應(yīng)用
確保你的 ??application.properties?? 或 ??application.yml?? 文件中沒有沖突的配置。
6. 測試
啟動你的 Spring Boot 應(yīng)用,然后訪問 ??http://localhost:8080/api/users/export-excel??,你應(yīng)該會下載到一個名為 ??users.xlsx?? 的 Excel 文件,其中包含用戶數(shù)據(jù)。
以上代碼展示了如何在 Spring MVC 中使用 Apache POI 導(dǎo)出 Excel 文件。你可以根據(jù)實際需求調(diào)整數(shù)據(jù)源和服務(wù)邏輯。在使用Spring MVC框架結(jié)合Apache POI庫來實現(xiàn)Excel文件的導(dǎo)出功能時,通常需要以下幾個步驟:
添加依賴:確保項目中已經(jīng)引入了Spring MVC和Apache POI的相關(guān)依賴。
創(chuàng)建Excel處理類:編寫一個類來處理Excel文件的生成邏輯。
控制器層:在Spring MVC的控制器中調(diào)用上述類的方法,并設(shè)置響應(yīng)頭以觸發(fā)文件下載。
1. 添加依賴
首先,在你的??pom.xml??文件中添加Apache POI的依賴:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.2</version>
</dependency>
2. 創(chuàng)建Excel處理類
接下來,創(chuàng)建一個類來處理Excel文件的生成。例如,創(chuàng)建一個名為??ExcelExporter??的類:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class ExcelExporter {
public void export(List<Map<String, Object>> data, HttpServletResponse response) throws IOException {
// 創(chuàng)建一個新的工作簿
Workbook workbook = new XSSFWorkbook();
// 創(chuàng)建一個工作表
Sheet sheet = workbook.createSheet("Data");
// 創(chuàng)建標(biāo)題行
Row headerRow = sheet.createRow(0);
int columnCount = 0;
for (String key : data.get(0).keySet()) {
Cell cell = headerRow.createCell(columnCount++);
cell.setCellValue(key);
}
// 填充數(shù)據(jù)
int rowCount = 1;
for (Map<String, Object> record : data) {
Row row = sheet.createRow(rowCount++);
columnCount = 0;
for (String key : record.keySet()) {
Cell cell = row.createCell(columnCount++);
Object value = record.get(key);
if (value instanceof String) {
cell.setCellValue((String) value);
} else if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Double) {
cell.setCellValue((Double) value);
}
// 可以根據(jù)需要添加更多的類型處理
}
}
// 設(shè)置響應(yīng)頭
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=data.xlsx");
// 寫入響應(yīng)輸出流
workbook.write(response.getOutputStream());
workbook.close();
}
}3. 控制器層
在Spring MVC的控制器中,調(diào)用??ExcelExporter??的??export??方法,并設(shè)置響應(yīng)頭以觸發(fā)文件下載:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class ExcelController {
@GetMapping("/export")
public void export(HttpServletResponse response) throws IOException {
List<Map<String, Object>> data = new ArrayList<>();
// 示例數(shù)據(jù)
Map<String, Object> record1 = new HashMap<>();
record1.put("Name", "John Doe");
record1.put("Age", 30);
record1.put("Email", "john.doe@example.com");
Map<String, Object> record2 = new HashMap<>();
record2.put("Name", "Jane Smith");
record2.put("Age", 25);
record2.put("Email", "jane.smith@example.com");
data.add(record1);
data.add(record2);
ExcelExporter exporter = new ExcelExporter();
exporter.export(data, response);
}
}總結(jié)
通過上述步驟,你可以在Spring MVC應(yīng)用中實現(xiàn)Excel文件的導(dǎo)出功能。這個過程包括添加必要的依賴、創(chuàng)建處理Excel文件的類以及在控制器中調(diào)用該類的方法并設(shè)置響應(yīng)頭以觸發(fā)文件下載。
以上就是SpringMVC框架使用 Apache POI實現(xiàn)導(dǎo)出Excel的詳細(xì)內(nèi)容,更多關(guān)于SpringMVC POI導(dǎo)出Excel的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring Boot JDBC 連接數(shù)據(jù)庫示例
本篇文章主要介紹了Spring Boot JDBC 連接數(shù)據(jù)庫示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02
SpringBoot+MyBatis整合ClickHouse實踐記錄
本文介紹了如何使用SpringBoot、MyBatis和ClickHouse整合,包括添加依賴、配置數(shù)據(jù)源、創(chuàng)建實體類、Mapper接口、服務(wù)層和控制器的步驟,通過這些步驟,可以使Java應(yīng)用程序高效地與ClickHouse數(shù)據(jù)庫進行交互,感興趣的朋友跟隨小編一起看看吧2024-12-12
java中判斷字段真實長度的實例(中文2個字符,英文1個字符)
下面小編就為大家?guī)硪黄猨ava中判斷字段真實長度的實例(中文2個字符,英文1個字符)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01
詳解Java并發(fā)編程基礎(chǔ)之volatile
volatile作為Java多線程中輕量級的同步措施,保證了多線程環(huán)境中“共享變量”的可見性。這里的可見性簡單而言可以理解為當(dāng)一個線程修改了一個共享變量的時候,另外的線程能夠讀到這個修改的值。本文將詳解介紹Java并發(fā)編程基礎(chǔ)之volatile2021-06-06
java中instanceof 關(guān)鍵字作用和實際用途詳解
這篇文章主要介紹了java中instanceof 關(guān)鍵字作用和實際用途,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04

