?? 前言
歡迎來到我的技術小宇宙!?? 這里不僅是我記錄技術點滴的后花園,也是我分享學習心得和項目經(jīng)驗的樂園。?? 無論你是技術小白還是資深大牛,這里總有一些內(nèi)容能觸動你的好奇心。??
?? 洛可可白:個人主頁
?? 個人專欄:?前端技術 ?后端技術
?? 個人博客:洛可可白博客
?? 代碼獲取:bestwishes0203
?? 封面壁紙:洛可可白wallpaper
標題:Spring Boot中Excel數(shù)據(jù)導入導出的高效實現(xiàn)
摘要
在企業(yè)級應用中,Excel文件的導入導出是一個常見的需求。本文將介紹如何在Spring Boot項目中使用EasyExcel庫實現(xiàn)Excel文件的導入導出功能。我們將通過實際的代碼示例,展示如何讀取和寫入Excel文件,以及如何通過自定義監(jiān)聽器來增強數(shù)據(jù)處理的靈活性。
1. 依賴添加
首先,我們需要在項目的pom.xml
文件中添加EasyExcel的依賴。
<!-- 導出excel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.2.1</version>
</dependency>
2. 自定義監(jiān)聽器(可選)
為了增強數(shù)據(jù)處理的靈活性,我們可以創(chuàng)建一個自定義監(jiān)聽器來校驗Excel文件中的數(shù)據(jù)。例如,我們可以校驗用戶名稱是否重復,或者數(shù)據(jù)格式是否正確。
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.xiaohe.uploadimage.entity.User;
/**
* 自定義監(jiān)聽器,對下載的excel中的數(shù)據(jù)進行校驗
*/
public class UserListener extends AnalysisEventListener {
List<String> names = new ArrayList<>();
/**
* 每解析一行,回調(diào)該方法
*
* @param data
* @param context
*/
@Override
public void invoke(Object data, AnalysisContext context) {
//校驗名稱
String name = ((User) data).getU_name();
// if (StrUtil.isBlank(name)) {
// throw new RuntimeException(String.format("第%s行名稱為空,請核實", context.readRowHolder().getRowIndex() + 1));
// }
if (names.contains(name)) {
throw new RuntimeException(String.format("第%s行名稱已重復,請核實", context.readRowHolder().getRowIndex() + 1));
} else {
names.add(name);
}
}
/**
* 出現(xiàn)異?;卣{(diào)
*
* @param exception
* @param context
* @throws Exception
*/
@Override
public void onException(Exception exception, AnalysisContext context) throws Exception {
if (exception instanceof ExcelDataConvertException) {
/**從0開始計算*/
int columnIndex = ((ExcelDataConvertException) exception).getColumnIndex() + 1;
int rowIndex = ((ExcelDataConvertException) exception).getRowIndex() + 1;
String message = "第" + rowIndex + "行,第" + columnIndex + "列" + "數(shù)據(jù)格式有誤,請核實";
throw new RuntimeException(message);
} else if (exception instanceof RuntimeException) {
throw exception;
} else {
super.onException(exception, context);
}
}
/**
* 解析完,全部回調(diào)
*
* @param context
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
//解析完,全部回調(diào)邏輯實現(xiàn)
names.clear();
}
}
3. 實體類定義
我們需要定義一個實體類來映射Excel文件中的列。使用@ExcelProperty
注解來指定Excel列的名稱。
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
// ... 其他代碼 ...
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
// ... 實體類屬性和注解 ...
@ExcelProperty("賬號")
private String u_acc;
@ExcelProperty("密碼")
private String u_pwd;
@ExcelProperty("姓名")
private String u_name;
@ExcelProperty("性別")
private String u_sex;
@ColumnWidth(20)
@DateTimeFormat("yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd")
@ExcelProperty("生日")
private Date u_birth;
@ExcelProperty("角色")
private String u_ide;
@ExcelProperty("狀態(tài)")
private int u_statues;
@ColumnWidth(20)
@DateTimeFormat("yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ExcelProperty("創(chuàng)建日期")
private Date u_create_time;
}
4. 控制層實現(xiàn)
導出數(shù)據(jù)
在控制器中,我們提供一個接口來導出Excel文件。EasyExcel提供了便捷的API來生成Excel文件。
import com.alibaba.excel.EasyExcel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
// ... 其他代碼 ...
@RestController
public class ExcelController {
@Autowired
private ExcelMapper excelMapper;
@GetMapping("user")
public List<User> user() {
return excelMapper.selectUserAll();
}
/**
* 導出數(shù)據(jù)
*/
@GetMapping("exportExcel")
public void exportData(HttpServletResponse response) throws IOException {
// ... 導出數(shù)據(jù)代碼 ...
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("用戶表", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
List<User> users = excelMapper.selectUserAll();
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), User.class).sheet("用戶表").doWrite(users);
}
}
導入數(shù)據(jù)
同樣地,我們提供一個接口來處理Excel文件的導入。通過EasyExcel的讀取功能,我們可以將Excel文件中的數(shù)據(jù)轉(zhuǎn)換為Java對象。
import com.alibaba.excel.EasyExcel;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
// ... 其他代碼 ...
@RestController
public class ExcelController {
/**
* 導入數(shù)據(jù)
*/
@PostMapping("/importExcel")
public Integer importData(MultipartFile file) {
try {
//獲取文件的輸入流
InputStream inputStream = file.getInputStream();
List<User> lst = EasyExcel.read(inputStream) //調(diào)用read方法
//注冊自定義監(jiān)聽器,字段校驗可以在監(jiān)聽器內(nèi)實現(xiàn)
.registerReadListener(new UserListener())
.head(User.class) //對應導入的實體類
.sheet(0) //導入數(shù)據(jù)的sheet頁編號,0代表第一個sheet頁,如果不填,則會導入所有sheet頁的數(shù)據(jù)
.headRowNumber(1) //列表頭行數(shù),1代表列表頭有1行,第二行開始為數(shù)據(jù)行
.doReadSync(); //開始讀Excel,返回一個List<T>集合,繼續(xù)后續(xù)入庫操作
//模擬導入數(shù)據(jù)庫操作
for (User user : lst) {
Date date = user.getU_birth();
String form = String.format("%tF", date);
System.out.println(form);
}
return 1;
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
}
?? 結語
通過本文的介紹,我們學習了如何在Spring Boot項目中使用EasyExcel庫來實現(xiàn)Excel文件的導入導出。自定義監(jiān)聽器的引入使得數(shù)據(jù)處理更加靈活,能夠應對各種復雜的業(yè)務需求。EasyExcel的簡單易用和強大的功能,使得Excel文件處理變得高效和便捷。在實際開發(fā)中,開發(fā)者可以根據(jù)項目需求,選擇合適的庫來實現(xiàn)Excel文件的處理。文章來源:http://www.zghlxwxcb.cn/news/detail-840137.html
如果對你有幫助,點贊、收藏、關注是我更新的動力!??????文章來源地址http://www.zghlxwxcb.cn/news/detail-840137.html
?? 往期精彩回顧
- Spring Boot工程集成驗證碼生成與驗證功能教程
- 文章瀏覽閱讀1.3k次,點贊17次,收藏38次。
- Spring Boot 3項目集成Swagger3教程
- 文章瀏覽閱讀768次,點贊8次,收藏15次。
- Spring Boot中實現(xiàn)圖片上傳功能的兩種策略
- 文章瀏覽閱讀1.1k次,點贊11次,收藏22次。
- VS code搭建C/C++運行環(huán)境簡單易上手
- 文章瀏覽閱讀2.7k次,點贊8次,收藏5次。
- 入門指南:使用uni-app構建跨平臺應用
- 文章瀏覽閱讀1.2k次,點贊29次,收藏9次。
到了這里,關于Spring Boot中Excel數(shù)據(jù)導入導出的高效實現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!