当前位置:网站首页>Super easy to use [general excel import function]
Super easy to use [general excel import function]
2022-04-23 03:17:00 【Xiaodaoxian 97】
List of articles
I wrote a simple one before Excel Import function , You can look at this first : https://www.bilibili.com/video/BV1kf4y1i761?p=5
There's a demand recently , Make one Excel Batch import function , The specific steps are as follows :
One 、 demand
1-1、 Download the template (excel)
full name (2-4 Characters ) | Age (1-150) | Gender ( male / Woman ) |
---|
1-2、 Data filling and importing
full name (2-4 Characters ) | Age (1-150) | Gender ( male / Woman ) |
---|---|---|
Zhang Sanfeng | 20 | male |
Xiaodaoxian 97 | 24 | male |
Murong Xiaoxiao | 18 | women |
1-3、 Import results display
1-4、 Data validation rules
- The name cannot be empty and can only be 2-4 Characters
- Age cannot be empty and can only be 1-150
- Gender cannot be empty and can only be male / Woman
- The imported data cannot have two files with the same name , If it exists, the import fails
- If there is a person with the same name in the database, you can't import
Two 、 Plan ideas
Use the above Excel Import function , hold Excel The template data is parsed into the corresponding List<Map<String,Object>>
data .
Use data to format the corresponding data into the corresponding entity , Then check the corresponding data according to the conditions in turn .
In fact, in addition to the import data verification rules , Everything else is universal , For example, return field 、 analysis excel And encapsulate it into bean, Deal with abnormal data, etc .
3、 ... and 、 Code using
3-1、 Create a new one VO, For example, the field you import is name
、age
、gender
Then your entity should be as follows :
notes : omitted get 、set 、 And null parameter construction method
public class TestImportExcelVo {
/** * Header */
public final static String[] HEADER = {
"name","age","gender"};
/** * full name */
private String name;
/** * Age */
private String age;
/** * Gender */
private String gender;
}
You can see that the only difference is that there is one more constant HEADER
, Its rule is Import template field order
3-2、 Add a new one ImportExcel Implementation class of interface , Realize the check Method ( This interface is explained below )
@Service
public class TestImportExcelImpl implements ImportExcel<TestImportExcelVo> {
@Override
public String[] check(ImportItem importItem, List<TestImportExcelVo> successResult, List<ImportItem> errorResult) {
return new String[]{
"1",""};
}
}
3-3、 call
@RestController
public class ImportExcelController {
@Autowired
public TestImportExcelImpl testImportExcelImpl;
@PostMapping("/importExcel")
public Object importExcel(MultipartFile file) {
return testImportExcelImpl.importCheck(file, TestImportExcelVo.HEADER, TestImportExcelVo.class);
}
}
Four 、 Code ideas explain
In fact, it depends on the interface ImportExcel
There are two ways .
4-1、 Get ready
Two are used here bean as follows ( Removed get/set)
/** * Export error result set entity bean * * Because the error result set needs one more reason field * * @author Xiaodaoxian * @date 2021 year 8 month 4 Japan */
public class ImportItem<T> {
private String errorReason;
public T t;
}
/** * Import Excel Return result entity * * @author Xiaodaoxian * @date 2021-08-04 */
public class ImportResultVo<T> {
/** * Total number of lines */
private Integer totalRows;
/** * Wrong number of lines */
private Integer errorRows;
/** * Number of successful lines */
private Integer successRows;
/** * Failed result set */
private List<T> errorResults;
/** * Successful result set */
private List<T> successResults;
public ImportResultVo() {
}
public ImportResultVo(Integer totalRows,Integer errorRows,Integer successRows,List<T> errorResults,List<T> successResults) {
this.totalRows = totalRows;
this.errorRows = errorRows;
this.successRows = successRows;
this.errorResults =errorResults;
this.successResults = successResults;
}
}
4-2、importCheck Method
This is a default method to complete some general functions , Such as :excel analysis 、 Entity bean Package, etc
default ImportResultVo importCheck(MultipartFile file, String[] header,Class clazz){
// from excel The data parsed from it
List<Map<String, Object>> maps;
try {
maps = ExcelUtils.importExcel(file, header);
}catch (Exception e){
logger.error(" Parse failure , The data template is incorrect ",e);
throw new RuntimeException(" Parse failure , The data template is incorrect ");
}
if (CollectionUtils.isEmpty(maps)){
return new ImportResultVo(0,0,0,null,null);
}
// Step by step validation of the data
int totalRows = 0;
int successRows = 0;
int errorRows = 0;
List<T> successResult = new ArrayList<>(50);
List<ImportItem> errorResult = new ArrayList<>(50);
for (Map map : maps) {
ImportItem<T> importItem = new ImportItem();
totalRows ++;
try {
Object tmpT = JsonUtils.objectToPojo(map, clazz);
importItem.setT((T)tmpT);
}catch (Exception e) {
errorRows ++;
logger.error("bean switch views ", e);
continue;
}
String[] check = check(importItem, successResult, errorResult);
if ("1".equals(check[0])) {
successRows ++;
successResult.add(importItem.getT());
}else if ("2".equals(check[0])) {
errorRows ++;
importItem.setErrorReason(check[1]);
errorResult.add(importItem);
}else if ("3".equals(check[0])){
successRows --;
errorRows ++;
importItem.setErrorReason(check[1]);
errorResult.add(importItem);
}
}
return new ImportResultVo(totalRows,errorRows,successRows,errorResult,successResult);
}
4-3、check Method
This is an interface method , You need to implement specific verification rules by yourself
/** * * @param t The entity to be verified at present bean * @param successResult Verified correct result set * @param errorResult Result set of verified errors * @return The first parameter is the verification result , The second is the reason for failure * 1 success * 2 Normal failure ( For example, the field is empty , The field format is incorrect , Conflict with database, etc ) * 3 Abnormal failure ( Conflict with previously successful data , For example, the uniqueness field already exists ) * notes :【 Abnormal failure 】 When , You need to check Method to delete the previously successful data , And insert the previous data into errorResult Inside */
String[] check(ImportItem t, List<T> successResult, List<ImportItem> errorResult);
4-4、 Other
there excel We have already said before exporting tool classes , Here's a simple copy .
/** * Excel Import * @param file file * @param keys Data order */
public static List<Map<String, Object>> importExcel(MultipartFile file, String[] keys) throws Exception{
Workbook wb = null;
String fileName = file.getOriginalFilename();
if (fileName.endsWith("xls")) {
POIFSFileSystem pois = new POIFSFileSystem(file.getInputStream());
wb = new HSSFWorkbook(pois);
} else if (fileName.endsWith("xlsx")) {
wb = new XSSFWorkbook(file.getInputStream());
}
Sheet sheet = wb.getSheetAt(0);
int rowCount = sheet.getPhysicalNumberOfRows();
if (sheet.getRow( 1).getPhysicalNumberOfCells() != keys.length){
throw new RuntimeException(" Imported Excel Does not match the column of the template ");
}
List<Map<String,Object>> result = new ArrayList<>();
for (int i = 0; i < rowCount - 1; i++) {
Row row = sheet.getRow(i + 1);
Map<String,Object> tmp = new HashMap<>();
for (int j = 0;j < keys.length; j++){
Cell cell = row.getCell(j);
if(cell == null) {
tmp.put(keys[j], null);
}else {
// Convert type to line Spring
cell.setCellType(CellType.STRING);
tmp.put(keys[j], cell.getStringCellValue());
}
}
result.add(tmp);
}
return result;
}
Look at the video and explain the address :https://www.bilibili.com/video/BV1kf4y1i761
Pay attention to WeChat official account reply :xdxFrameSimple Access to the source code .
版权声明
本文为[Xiaodaoxian 97]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230315096166.html
边栏推荐
- Mise en service PID du moteur de codage (anneau de vitesse | anneau de position | suivant)
- Five tips for cross-border e-commerce in 2022
- Chapter 9 of C language programming (fifth edition of Tan Haoqiang) analysis and answer of exercises for users to establish their own data types
- [Mysql] LEFT函數 | RIGHT函數
- . net tip: talk about the problem that the scoped service cannot be obtained in the middleware structure
- Quartz. Www. 18fu Used in net core
- 为什么BI对企业这么重要?
- MySql关键字GROUP_CONCAT,组合连接查询
- Knowledge of software testing~
- ASP. Net 6 middleware series - execution sequence
猜你喜欢
Drawing polygons with < polygon / > circular array in SVG tag
《C语言程序设计》(谭浩强第五版) 第7章 用函数实现模块化程序设计 习题解析与答案
Web Course Design - his system
一套组合拳,打造一款 IDEA 护眼方案
2022T电梯修理考试模拟100题及在线模拟考试
Quartz. Www. 18fu Used in net core
Aspnetcore configuration multi environment log4net configuration file
Use of slice grammar sugar in C #
为什么BI对企业这么重要?
2022 P cylinder filling training test questions and simulation test
随机推荐
Use DFS to solve the problem of "number of dictionary rows"
The backtracking of stack is used to solve the problem of "the longest absolute path of file"
2022 Shandong Province safety officer C certificate work certificate question bank and online simulation examination
2022t elevator repair test simulation 100 questions and online simulation test
This new feature of C 11, I would like to call it the strongest!
一套组合拳,打造一款 IDEA 护眼方案
Drawing polygons with < polygon / > circular array in SVG tag
Tencent video price rise: earn more than 7.4 billion a year! Pay attention to me to receive Tencent VIP members, and the weekly card is as low as 7 yuan
2022山东省安全员C证上岗证题库及在线模拟考试
Mysql database, inconsistent index character set, slow SQL query, interface timeout
Use of slice grammar sugar in C #
[MySQL] left function | right function
A comprehensive understanding of static code analysis
一文了解全面静态代码分析
Huawei mobile ADB devices connection device is empty
be based on. NETCORE development blog project starblog - (2) environment preparation and creation project
socket編程 send()與 recv()函數詳解
General test technology [II] test method
Node configuration environment CMD does not take effect
Seminar playback video: how to improve Jenkins' ability to become a real Devops platform