从excel读取数据并使用spring boot jpa存储在db中。
我的Excel看起来像这样。
address Name
---------------------
XYZ ABC
ZX BC
我的服务等级:
public class SpreadSheetService{
@Autowired
SpreadSheetRepo spreadSheetRepo;
private ModelMapper modelMapper=new ModelMapper() ;
public void readExcelSheet() throws IOException {
FileInputStream file = new FileInputStream(new File("src/main/resources/spreadsheet.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet getSheet=workbook.getSheet("Sheet1");
List<SEntity> dataList= modelMapper.map(result(getSheet), new TypeToken<List<SEntity>>(){}.getType());
spreadSheetRepo.saveAll(dataList);
}
List<SEntity> result(XSSFSheet getSheet){
Iterator<Row> rowItr = getSheet.iterator();
boolean flag=false;
List<SEntity> list=new ArrayList<>();
while(rowItr.hasNext()) {
Row row = rowItr.next();
SEntity obj=new SEntity();
Iterator<Cell> cellItr = row.cellIterator();
if(flag==true) {
while(cellItr.hasNext()) {
Cell cell = cellItr.next();
int index = cell.getColumnIndex();
switch(index) {
case 0:
obj.setAddress(cell.toString());
break;
case 1:
obj.setName(cell.toString());
break;
}
}
list.add(obj);
}
flag=true;
}
return list;
}
}
我的实体类别:
@Entity
@Table(name="spreadsheet")
@Data
public class SEntity {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
int id;
@Column(name="name")
String name;
@Column(name="address")
String address;
}
我的回购类别:
@Repository
public interface SpreadSheetRepo extends CrudRepository<SEntity,Integer> {
}
以上代码按预期工作正常。但是如果我有30列或更多列怎么办?对我来说,定义索引0到30或基于切换情况下的列数对我来说并不好。
还有其他方法可以实现这种情况吗?