前言:相信很多朋友在进行项目开发的时候都会面临着excel表格的导入导出功能,现在我给大家分享一下demo。
1.导入依赖,poi包支持的,不要出错了!!!
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
poi的支持我得电脑的版本是:<poi.version>4.1.0</poi.version>
2.导入文件,话不多说直接上代码
@Override
public Boolean batchImportExl(InputStream in) {
Boolean returnB = Boolean.TRUE;
StringBuffer returnStr = new StringBuffer();
try {
Workbook wb = new XSSFWorkbook(in);
Sheet sheet = wb.getSheetAt(0);
int rowNo = sheet.getLastRowNum();
Row row = null;
Cell cell = null;
List<TStaffInfo> addInfos = Lists.newArrayList();
for (int i = 2; i <= rowNo; i++) {
TStaffInfo staffInfo = new TStaffInfo();
row = sheet.getRow(i);
if (row.getCell(1)!=null){
cell = row.getCell(1);
cell.setCellType(CellType.STRING);
staffInfo.setName(cell.getStringCellValue());
}
row = sheet.getRow(i);
if (row.getCell(2)!=null){
cell = row.getCell(2);
cell.setCellType(CellType.STRING);
staffInfo.setSex((cell.getStringCellValue().equals("男"))?1:2);
}
row = sheet.getRow(i);
if (row.getCell(3)!=null){
cell = row.getCell(3);
cell.setCellType(CellType.STRING);
staffInfo.setNation(cell.getStringCellValue());
}
row = sheet.getRow(i);
if (row.getCell(4)!=null){
cell = row.getCell(4);
cell.setCellType(CellType.STRING);
staffInfo.setPoliticalOutlook(cell.getStringCellValue());
}
row = sheet.getRow(i);
if (Strings.isNotBlank(cell.getStringCellValue())){
cell = row.getCell(5);
cell.setCellType(CellType.STRING);
staffInfo.setTeam(cell.getStringCellValue());
}
row = sheet.getRow(i);
if (row.getCell(6)!=null){
cell = row.getCell(6);
cell.setCellType(CellType.STRING);
staffInfo.setPost(cell.getStringCellValue());
}
row = sheet.getRow(i);
if (row.getCell(7)!=null){
cell = row.getCell(7);
cell.setCellType(CellType.STRING);
staffInfo.setServerCommunity(cell.getStringCellValue());
}
}
if (CollectionUtils.isNotEmpty(addInfos)){
//将姓名一样的数据的角色信息合并
for (int i=1;i<addInfos.size()-1;i++){
int j = 1;
TStaffInfo staffInfo = addInfos.get(i);
while (Optional.ofNullable(addInfos.get(i+j)).isPresent() && StringUtils.isEmpty(addInfos.get(i+j).getName())){
staffInfo.setServerCommunity(addInfos.get(i+j).getServerCommunity()+","+staffInfo.getServerCommunity());
j++;
}
}
addInfos = addInfos.stream().filter(e->StringUtils.isNotEmpty(e.getName())).collect(Collectors.toList());
//添加数据
saveBatch(addInfos);
}
}catch (IOException e){
returnB = Boolean.FALSE;
log.error(e.getMessage(), e);
}
return returnB;
}
3.postman直接请求
将上传的格式改为file
大功告成,希望给有帮助的朋友,能点个关注,一键三联,你们支持将会是我写下去的动力!!!!