Excel import function (easyexcel)
The first step: import the package in the pom file
< dependency>
< groupId> com.alibaba</ groupId>
< artifactId> easyexcel</ artifactId>
</ dependency>
< dependency>
< groupId> org.apache.xmlbeans</ groupId>
< artifactId> xmlbeans</ artifactId>
</ dependency>
Step 2: Create an Excel entity class
@Data
public class ExcelDictDTO {
@ExcelProperty ( "id" )
private Long id;
@ExcelProperty ( "姓名" )
private String name;
}
Step 3: Create a listener
@Slf4j
@NoArgsConstructor
public class ExcelDictDTOListener extends AnalysisEventListener < ExcelDictDTO > {
private static final int BATCH_COUNT = 5 ;
List < ExcelDictDTO > list = new ArrayList ( ) ;
private DictMapper dictMapper;
public ExcelDictDTOListener ( DictMapper dictMapper) {
this . dictMapper = dictMapper;
}
@Override
public void invoke ( ExcelDictDTO data, AnalysisContext context) {
log. info ( "解析到一条记录: {}" , data) ;
list. add ( data) ;
if ( list. size ( ) >= BATCH_COUNT) {
saveData ( ) ;
list. clear ( ) ;
}
}
@Override
public void doAfterAllAnalysed ( AnalysisContext context) {
saveData ( ) ;
log. info ( "所有数据解析完成!" ) ;
}
private void saveData ( ) {
log. info ( "{}条数据,开始存储数据库!" , list. size ( ) ) ;
dictMapper. insertBatch ( list) ;
log. info ( "存储数据库成功!" ) ;
}
}
< insert id = " insertBatch" >
insert into dict (id,name) values
< foreach collection = " list" item = " item" index = " index" separator = " ," >
(#{item.id},#{item.name}})
</ foreach>
</ insert>
Step 4: Service layer creates a listener instance
@Transactional ( rollbackFor = {
Exception . class } )
@Override
public void importData ( InputStream inputStream) {
EasyExcel . read ( inputStream, ExcelDictDTO . class , new ExcelDictDTOListener ( baseMapper) ) . sheet ( ) . doRead ( ) ;
log. info ( "importData finished" ) ;
}
Step 5: Controller layer receives client upload
@Api ( tags = "数据字典管理" )
@RestController
@RequestMapping ( "/admin/core/dict" )
@Slf4j
@CrossOrigin
public class AdminDictController {
@Resource
private DictService dictService;
@ApiOperation ( "Excel批量导入数据字典" )
@PostMapping ( "/import" )
public R batchImport (
@ApiParam ( value = "Excel文件" , required = true )
@RequestParam ( "file" ) MultipartFile file) {
try {
InputStream inputStream = file. getInputStream ( ) ;
dictService. importData ( inputStream) ;
return R . ok ( ) . message ( "批量导入成功" ) ;
} catch ( Exception e) {
throw new BusinessException ( ResponseEnum . UPLOAD_ERROR, e) ;
}
}
}
Step 6: Add mapper release configuration Note: Because all resource files in the src/main/java directory of the maven project are not published to the target directory by default, we need to add the xml configuration file release in pom.xml configuration
< build>
< resources>
< resource>
< directory> src/main/java</ directory>
< includes>
< include> **/*.xml</ include>
</ includes>
< filtering> false</ filtering>
</ resource>
</ resources>
</ build>