AUTOPOI导入Excel文件(可获取表头数据)
Controller.java部分代码
@Autowired
private IAshContentService ashContentService;
public Result < ? > importExcel ( HttpServletRequest request, HttpServletResponse response) throws IOException {
MultipartHttpServletRequest multipartRequest = ( MultipartHttpServletRequest ) request;
Map < String , MultipartFile > fileMap = multipartRequest. getFileMap ( ) ;
for ( Map. Entry < String , MultipartFile > entity : fileMap. entrySet ( ) ) {
MultipartFile file = entity. getValue ( ) ;
InputStream inputStream = file. getInputStream ( ) ;
HSSFWorkbook wb = new HSSFWorkbook ( inputStream) ;
HSSFSheet sheetAt = wb. getSheetAt ( 0 ) ;
Row row = sheetAt. getRow ( 0 ) ;
Date nowday = row. getCell ( 0 ) . getDateCellValue ( ) ;
ImportParams params = new ImportParams ( ) ;
params. setTitleRows ( 1 ) ;
params. setHeadRows ( 1 ) ;
params. setSheetNum ( 1 ) ;
params. setNeedSave ( true ) ;
try {
List < AshContent > list = ExcelImportUtil . importExcel ( file. getInputStream ( ) , AshContent . class , params) ;
long start = System . currentTimeMillis ( ) ;
list. stream ( ) . forEach ( e-> {
e. setNowday ( nowday) ;
} ) ;
ashContentService. saveBatch ( list) ;
log. info ( "消耗时间" + ( System . currentTimeMillis ( ) - start) + "毫秒" ) ;
return Result . ok ( "文件导入成功!数据行数:" + list. size ( ) ) ;
} catch ( Exception e) {
String msg = e. getMessage ( ) ;
log. error ( msg, e) ;
if ( msg!= null && msg. indexOf ( "Duplicate entry" ) >= 0 ) {
return Result . error ( "文件导入失败:有重复数据!" ) ;
} else {
return Result . error ( "文件导入失败:" + e. getMessage ( ) ) ;
}
} finally {
try {
file. getInputStream ( ) . close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
return Result . error ( "文件导入失败!" ) ;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
Service.java部分代码
Boolean saveBatch ( List < AshContent > list) ;
void deleteByNowday ( Date nowday) ;
@Resource
private AshContentMapper mapper;
@Override
public Boolean saveBatch ( List < AshContent > list) {
Boolean response = mapper. insertBatch ( list) ;
return response;
}
@Override
public void deleteByNowday ( Date nowday) {
mapper. deleteByNowday ( nowday) ;
}
Mapper.java部分代码
Boolean insertBatch ( List < AshContent > list) ;
void deleteByNowday ( @Param ( "nowday" ) Date nowday) ;
mapper.xml部分代码
< insert id = " insertBatch" >
INSERT INTO `table`(
id
)
values
< foreach collection = " list" item = " item" separator = " ," >
(
#{item.id}
)
foreach>
insert>
< delete id = " deleteByNowday" >
delete from table where xxx.nowday=#{nowday}
delete>