This project is a simple Excel file reader. Using the ExcelReader.java
, and passing a xlsx file and a mapper class that implements the IRowMapper
, you get a result list to yout own custom class.
The ExcelReader class uses a Generic class to return a typed list, uses only its own custom class, and pass the file and the mapper. The implementation is based in Apache POI resources to read the file, and it gets the rows and columns.
public class ExcelReader<T> {
private InputStream file;
private IRowMapper<T> rowMapper;
private boolean skipFirstLine = true;
public ExcelReader(InputStream inputStream, IRowMapper<T> rowMapper) {
this.file = inputStream;
this.rowMapper = rowMapper;
}
public ExcelReader(InputStream inputStream, IRowMapper<T> rowMapper, boolean skipFirstLine) {
this.file = inputStream;
this.rowMapper = rowMapper;
this.skipFirstLine = skipFirstLine;
}
public List<T> read() throws Exception {
if(file == null) {
throw new Exception("File not found");
}
var items = new ArrayList<T>();
try {
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
var firstLine = this.skipFirstLine ? 1 : 0;
for(int i = firstLine; i < sheet.getPhysicalNumberOfRows(); i++) {
XSSFRow row = sheet.getRow(i);
T item = rowMapper.map(row);
items.add(item);
}
}
catch (IOException e) {
e.printStackTrace();
}
return items;
}
}
public interface IRowMapper<T> {
T map(XSSFRow row);
}
Import a list of students with name, email and level;
NAME | LEVEL | |
---|---|---|
Marcio | [email protected] | master |
Teste | [email protected] | smarter |
Teste 2 | [email protected] | intermediate |
java/resources/data/students.xlsx
@Data
public class StudentDTO {
private String email;
private String name;
private String level;
}
public class StudentDTORowMapper implements IRowMapper<StudentDTO> {
@Override
public StudentDTO map(XSSFRow row) {
StudentDTO student = new StudentDTO();
student.setName(String.valueOf(row.getCell(0)));
student.setEmail(String.valueOf(row.getCell(1)));
student.setLevel(String.valueOf(row.getCell(2)));
return student;
}
}
@SpringBootApplication
public class ExcelReaderApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(ExcelReaderApplication.class, args);
var file = new ClassPathResource("data/students.xlsx");
var excelReader = new ExcelReader<StudentDTO>(file.getInputStream(), new StudentDTORowMapper());
var items = excelReader.read();
}
}
- StudentDTO(email=[email protected], name=Marcio, level=master)
- StudentDTO(email=[email protected], name=Teste, level=starter)
- StudentDTO(email=[email protected], name=Teste 2, level=intermediate)
Developed by Marcio Costa.