当前位置:网站首页>[untitled]
[untitled]
2022-04-23 08:07:00 【Code generation】
Java Import complex excel Table data to database
Take a look at the... To be imported into the database excel How complex the table data is ? Directly above !

If you want to import it into the database, you need to parse it into what I need , As shown in the figure below .

After comparison , If we don't find it, we need to make a comparison of Figure 1 excel To analyze , Go straight to the code !
controller layer
@PostMapping("/xfkylImport")
@ApiOperation(value = " Import complex excel Table data ")
public R<Boolean> xfkylImport(@ApiParam(value = " File object ") @RequestBody MultipartFile file) {
Boolean aBoolean = importTableService.xfkylImport(file);
return R.OK(aBoolean);
}
service layer
/** * Import complex excel Table data * * @param file file * @return result */
public Boolean xfkylImport(MultipartFile file) {
// Look up the code table :excel No unit number , So we can only check the code table first , Then insert the unit number of the code table into the corresponding table data to be imported
List<IcDwbmk> icDwbmks = icDwbmkService.listAll();
Workbook workbook;
try {
// according to file establish excel
workbook = WorkbookFactory.create(file.getInputStream());
} catch (Exception e) {
throw new CustomException(" Import failed , Please check whether the import template is correct ");
}
// Get the first one sheet page
Sheet xssSheet0 = workbook.getSheetAt(0);
// Get the first and last lines
int rows1 = xssSheet0.getFirstRowNum();
int rows2 = xssSheet0.getLastRowNum();
// Create a temporary object to receive parameters
List<IcDreportXfkylVo> entities = new ArrayList<>();
List<String> str = new ArrayList<>();
// Let's start :j representative excel The line of ,k representative excel The column of
// Loop traversal : Discard the first row header data
for (int j = rows1 + 1; j <= rows2; j++) {
// Create temporary objects
IcDreportXfkylVo excelVo = new IcDreportXfkylVo();
// Get current row
Row row3 = xssSheet0.getRow(j);
// If there is no data in the current line, directly end the cycle
if (null == row3) continue;
// Traverse all the columns in the row
int firstCellNum = row3.getFirstCellNum();
int lastCellNum = row3.getLastCellNum();
// Number of circular columns : Discard the first column , Here, according to the business needs lastCellNum - 2 operation
for (int k = firstCellNum + 1; k < lastCellNum - 2; k++) {
// Get cell value , Whether the cells are merged or not , You can get
String value = getSheelValue(xssSheet0, j, k);
// Column data is empty , End the cycle
if (StrUtil.isBlank(value)) continue;
// analysis excel The date value in , And stored in the collection
if (j == 1 && k == 1) {
// Date formatting
Date date = Convert.toDate(value);
String datee = DateUtil.format(date, "yyyy-MM-dd");
str.add(datee);
}
// Abandon these two columns
if (k == 10 || k > 17) continue;
// =========== If the conditions are met, the cycle will be ended directly start( According to the actual needs )===========
if (" Data date ".equals(value)) continue;
if (" Test Category 1 ".equals(value)) continue;
if (" Test Category II ".equals(value)) continue;
if (j < 4) continue;
if (j == 5) continue;
if (j > 12) continue;
// =========== If the conditions are met, the cycle will be ended directly end( According to the actual needs )===========
// Obtain that the company name in the first column matches the name in the code table , If it is the same, take out the unit number in the coding table
if (k == 1) {
// There is a name that does not correspond to , Manually rename .
if (" So and so company 1".equals(value)) {
value = " So and so company 2";
}
// Take out the corresponding number of each unit
String finalValue = value;
String s = icDwbmks.stream().filter(a -> finalValue.contains(a.getDwmc())).map(IcDwbmk::getDwbh).collect(Collectors.joining());
excelVo.setDwbh(s);
excelVo.setDwmc(value.replace(" So and so company 2", " So and so company 1"));
}
try {
if (StringUtils.isNumeric(value)) {
// Assign the value of the current column to the corresponding attribute field , The corresponding value of each column And list Form storage of
if (k == 2) excelVo.setSjlx1(Integer.valueOf(value));
if (k == 3) excelVo.setSjlx2(Integer.valueOf(value));
if (k == 4) excelVo.setSjlx3(Integer.valueOf(value));
if (k == 5) excelVo.setSjlx4(Integer.valueOf(value));
if (k == 6) excelVo.setSjlx5(Integer.valueOf(value));
if (k == 7) excelVo.setSjlx6(Integer.valueOf(value));
if (k == 8) excelVo.setSjlx7(Integer.valueOf(value));
if (k == 9) excelVo.setSjlx8(Integer.valueOf(value));
if (k == 11) excelVo.setSjlx9(Integer.valueOf(value));
if (k == 12) excelVo.setSjlx10(Integer.valueOf(value));
if (k == 13) excelVo.setSjlx11(Integer.valueOf(value));
if (k == 14) excelVo.setSjlx12(Integer.valueOf(value));
if (k == 15) excelVo.setSjlx13(Integer.valueOf(value));
if (k == 16) excelVo.setSjlx14(Integer.valueOf(value));
}
} catch (Exception e) {
throw new CustomException(" Import failed , Please check whether the import template is correct ");
}
}
//j Each cycle will store a set of data , There will be a lot of empty objects , Empty objects will be emptied later
entities.add(excelVo);
}
if (entities.size() > 0) {
// excel Parsing complete : Empty the empty objects in the collection
entities.removeAll(Collections.singleton(new IcDreportXfkylVo()));
// Traverse : Assign the date value to the data
for (IcDreportXfkylVo item :
entities) {
item.setDatee(str.get(0));
}
// Manually catching exceptions
try {
// Bulk insert data
Integer integer = icDreportXfkylMapper.insertBatch(entities);
if (integer > 0) {
return true;
}
} catch (Exception e) {
throw new CustomException(" Import failed , Please check whether the import template is correct ");
}
}
throw new CustomException(" Import failed , Please check the imported excel Whether the table data is correct ");
}
/** * Get cell contents , Includes the of merged cells * * @param sheet sheet Forms * @param row Current line subscript * @param col Current column subscript * @return result */
public String getSheelValue(Sheet sheet, int row, int col) {
// Get the number of merged areas
int mergedRegions = sheet.getNumMergedRegions();
// Number of traversing merge regions
for (int i = 0; i < mergedRegions; i++) {
// Specifies the merge area at the index
CellRangeAddress region = sheet.getMergedRegion(i);
// Line start subscript
int firstRow = region.getFirstRow();
// End of line subscript
int lastRow = region.getLastRow();
// Column start subscript
int firstColumn = region.getFirstColumn();
// Column end subscript
int lastColumn = region.getLastColumn();
if (row >= firstRow && row <= lastRow) {
if (col >= firstColumn && col <= lastColumn) {
Row fRow = sheet.getRow(firstRow);
Cell cell = fRow.getCell(firstColumn);
// All contents have been processed in string form
cell.setCellType(CellType.STRING);
// Get the value of the cell as a string
return cell.getStringCellValue();
}
}
}
Cell cell = sheet.getRow(row).getCell(col);
// All contents have been processed in string form
cell.setCellType(CellType.STRING);
return cell.getStringCellValue();
}
after service Layer resolution , Here we have successfully completed the effect of Figure 2 , The final effect is “entities” This List It's in the assembly , Then insert the set data into the database in batches .
Friends with similar needs , Copy my code directly and change it according to my own needs , According to the debug Step by step debugging , It will succeed in the end .
版权声明
本文为[Code generation]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230645255959.html
边栏推荐
- Research on software security based on NLP (2)
- 3C裝配中的機械臂運動規劃
- 巨头押注的全屋智能,正在驱动海信、华为、小米们「自我革命」
- CTF attack and defense world brush questions 51-
- 输入 “ net start mysql ”,出现 “ 发生系统错误 5。 拒绝访问 ” 。问题详解
- 数据库之Mysql——概述安装篇
- Intranet security attack and defense: a practical guide to penetration testing (6): domain controller security
- Go语学习笔记 - 结构体 | 从零开始Go语言
- strcat()、strcpy()、strcmp()、strlen()
- [programming practice / embedded competition] learning record of embedded competition (I): establishment of TCP server and web interface
猜你喜欢

雲計算技能大賽 -- openstack私有雲環境 第一部分

1216_MISRA_C规范学习笔记_控制流的规则要求

Intranet penetration series: icmpsh of Intranet tunnel

Three minutes to teach you to use Houdini fluid > > to solve particle fluid droplets

分布式服务治理Nacos

SAP self created table log function is enabled

Ctf-misc summary

内网渗透系列:内网隧道之icmptunnel(jamesbarlow师傅的)

Concours de compétences en informatique en nuage - - première partie de l'environnement cloud privé openstack

几种智能机器人室内定位方法对比
随机推荐
Fibula dynamic programming
MYSQL——第一章节(数据类型2)
Summary of facial classics
LeetCode15. 三数之和
Ignis公链的NFT生态发展:Unicorn.art的捐赠开发之路
智能名片小程序名片详情页功能实现关键代码
Dvwa 靶场练习记录
Internal network security attack and defense: a practical guide to penetration testing (8): Authority maintenance analysis and defense
[programming practice / embedded competition] learning record of embedded competition (I): establishment of TCP server and web interface
NLLLoss+log_SoftMax=CE_Loss
内网渗透系列:内网隧道之icmp_tran
几种智能机器人室内定位方法对比
A series of articles, a summary of common vulnerabilities of Web penetration (continuously updated)
[go]常见的并发模型[泛型版]
php生成短链接:将数字转成字母,将字母转成数字
聊聊接口幂等与消费幂等的本质
Intranet penetration series: dns2tcp of Intranet tunnel
雲計算技能大賽 -- openstack私有雲環境 第一部分
vivo,硬件安全的爱与雷霆
CSV Column Extract列提取