Skip to content

Commit 2af557a

Browse files
committed
Fixed several bugs. I added the method that creates a sheet if it doesn't exist. I added a method that counts all rows of all sheets. I added a method that opens a workbook starting from the input file.
1 parent d3b2fcb commit 2af557a

File tree

12 files changed

+180
-131
lines changed

12 files changed

+180
-131
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package exceptions;
2+
3+
public class HeaderNotPresentException extends Exception {
4+
5+
public HeaderNotPresentException() {
6+
super();
7+
}
8+
9+
public HeaderNotPresentException(String message) {
10+
super(message);
11+
}
12+
13+
public HeaderNotPresentException(String message, Throwable cause) {
14+
super(message, cause);
15+
}
16+
}

src/main/java/samples/convertExcelFileToObjectsSample/Employee.java renamed to src/main/java/samples/convertExcelFileToObjectsSample/Car.java

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,27 +14,22 @@
1414

1515
@AllArgsConstructor
1616
@NoArgsConstructor
17-
@Getter
1817
@Setter
1918
@ToString
2019
@ExcelHeaderStyle(cellColor = IndexedColors.ORANGE, horizontal = HorizontalAlignment.RIGHT, vertical = VerticalAlignment.BOTTOM, autoSize = true)
2120
@ExcelBodyStyle(cellColor = IndexedColors.LIGHT_ORANGE, horizontal = HorizontalAlignment.RIGHT, vertical = VerticalAlignment.BOTTOM)
22-
public class Employee {
21+
public class Car {
2322

24-
@ExcelField(name = "LAST NAME")
25-
private String lastName;
26-
@ExcelField(name = "NAME")
27-
private String name;
28-
@ExcelField(name = "AGE")
29-
private Integer age;
30-
@ExcelField(name = "BIRTHDAY")
31-
private LocalDate birthday;
32-
@ExcelField(name = "HIRE DATE")
33-
private Date hireDate;
34-
@ExcelField(name = "SALARY (€)")
35-
private Double salary;
36-
@ExcelField(name = "LAST SIGN IN")
37-
private LocalDateTime lastSignIn;
38-
@ExcelField(name = "IS IN OFFICE")
39-
private Boolean isInOffice;
23+
@ExcelField(name = "BRAND")
24+
private String brand;
25+
@ExcelField(name = "MODEL")
26+
private String model;
27+
@ExcelField(name = "YEAR")
28+
private Integer year;
29+
@ExcelField(name = "RELEASE DATE")
30+
private LocalDate releaseDate;
31+
@ExcelField(name = "FIRST SALE")
32+
private Date firstSale;
33+
@ExcelField(name = "LAST SALE")
34+
private LocalDateTime lastSale;
4035
}

src/main/java/samples/convertExcelFileToObjectsSample/Main.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ public class Main {
1010

1111
public static void main(String[] args) {
1212

13-
File file = new File("./src/main/resources/employee.xlsx");
13+
File file = new File("./src/main/resources/car.xlsx");
1414

1515
try {
1616
System.out.println("Start the conversion...");
1717
ExcelConverter excelConverter = new ExcelConverterImpl();
18-
List<Employee> employees = (List<Employee>) excelConverter.excelToObjects(file, Employee.class);
18+
List<Car> employees = (List<Car>) excelConverter.excelToObjects(file, Car.class);
1919
System.out.println("The list is ready. List: " + employees.toString());
2020
} catch (Exception e) {
2121
System.err.println("There was an error. Check the console");

src/main/java/samples/countAllRowsSample/Main.java

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,24 @@
44
import tools.implementations.ExcelUtilsImpl;
55

66
import java.io.File;
7+
import java.util.List;
78

89
public class Main {
910

1011
public static void main(String[] args) {
1112

1213
ExcelUtils excelUtils = new ExcelUtilsImpl();
13-
File file = new File("./src/main/resources/employee.xlsx");
14+
File file = new File("./src/main/resources/car.xlsx");
1415

1516
try {
16-
int totalRows = excelUtils.countAllRows(file, true);
17+
int totalRows = excelUtils.countAllRows(file, "car");
1718
System.out.println("Total: " + totalRows);
18-
int totalRowsWithoutEmpty = excelUtils.countAllRows(file, false, "Employee");
19+
int totalRowsWithoutEmpty = excelUtils.countAllRows(file, "car", false);
1920
System.out.println("Total without empty rows: " + totalRowsWithoutEmpty);
21+
List<Integer> totalRowsOfSheets = excelUtils.countAllRowsOfAllSheets(file);
22+
System.out.println("Total of all sheets: " + totalRowsOfSheets);
23+
List<Integer> totalRowsOfSheetsWithoutEmpty = excelUtils.countAllRowsOfAllSheets(file, false);
24+
System.out.println("Total of all sheets without empty rows : " + totalRowsOfSheetsWithoutEmpty);
2025
} catch (Exception e) {
2126
System.err.println("There was an error. Check the console");
2227
throw new RuntimeException(e);

src/main/java/tools/implementations/ExcelConverterImpl.java

Lines changed: 30 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,8 @@
44
import annotations.ExcelField;
55
import annotations.ExcelHeaderStyle;
66
import enums.ExcelExtension;
7-
import exceptions.ExtensionNotValidException;
8-
import exceptions.FileAlreadyExistsException;
9-
import exceptions.OpenWorkbookException;
10-
import exceptions.SheetNotFoundException;
7+
import exceptions.*;
118
import org.apache.commons.beanutils.PropertyUtils;
12-
import org.apache.commons.io.FilenameUtils;
139
import org.apache.poi.ss.usermodel.*;
1410
import tools.interfaces.ExcelConverter;
1511
import tools.interfaces.ExcelSheetUtils;
@@ -82,12 +78,11 @@ public File objectsToExcel(List<?> objects, Class<?> clazz, String filename, Exc
8278

8379
@Override
8480
public File objectsToExcel(List<?> objects, Class<?> clazz, String path, String filename, ExcelExtension extension, Boolean writeHeader) throws IllegalAccessException, IOException, FileAlreadyExistsException {
85-
8681
/* Open file */
8782
String pathname = this.getPathname(path, filename, extension);
8883
File file = new File(pathname);
8984

90-
if(file.exists()) {
85+
if (file.exists()) {
9186
throw new FileAlreadyExistsException("There is already a file with this pathname: " + file.getAbsolutePath());
9287
}
9388

@@ -102,14 +97,14 @@ public File objectsToExcel(List<?> objects, Class<?> clazz, String path, String
10297
int cRow = 0;
10398

10499
/* Write header */
105-
if(writeHeader) {
106-
CellStyle headerCellStyle = createHeaderCellStyle(workbook, clazz);
100+
if (writeHeader) {
101+
CellStyle headerCellStyle = this.createHeaderCellStyle(workbook, clazz);
107102
this.writeExcelHeader(sheet, fields, cRow++, headerCellStyle);
108103
}
109104

110105
/* Write body */
111106
for (Object object : objects) {
112-
CellStyle bodyCellStyle = createBodyStyle(workbook, clazz);
107+
CellStyle bodyCellStyle = this.createBodyStyle(workbook, clazz);
113108
this.writeExcelBody(workbook, sheet, fields, object, cRow++, bodyCellStyle, clazz);
114109
}
115110

@@ -124,15 +119,15 @@ public File objectsToExcel(List<?> objects, Class<?> clazz, String path, String
124119
}
125120

126121
@Override
127-
public List<?> excelToObjects(File file, Class<?> clazz) throws ExtensionNotValidException, IOException, OpenWorkbookException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SheetNotFoundException {
122+
public List<?> excelToObjects(File file, Class<?> clazz) throws ExtensionNotValidException, IOException, OpenWorkbookException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SheetNotFoundException, HeaderNotPresentException {
128123
return excelToObjects(file, clazz, null);
129124
}
130125

131126
@Override
132-
public List<?> excelToObjects(File file, Class<?> clazz, String sheetName) throws ExtensionNotValidException, IOException, OpenWorkbookException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException, SheetNotFoundException {
133-
127+
public List<?> excelToObjects(File file, Class<?> clazz, String sheetName) throws ExtensionNotValidException, IOException, OpenWorkbookException, InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException, SheetNotFoundException, HeaderNotPresentException {
134128
/* Check extension */
135-
String extension = checkExtension(file.getName());
129+
ExcelUtils excelUtils = new ExcelUtilsImpl();
130+
String extension = excelUtils.checkExtension(file.getName());
136131

137132
/* Open file excel */
138133
ExcelWorkbookUtils excelWorkbookUtils = new ExcelWorkbookUtilsImpl();
@@ -146,17 +141,16 @@ public List<?> excelToObjects(File file, Class<?> clazz, String sheetName) throw
146141
/* Retrieving header names */
147142
Field[] fields = clazz.getDeclaredFields();
148143
this.setFieldsAccessible(fields);
149-
Map<Integer, String> headerMap = getHeaderNames(sheet, fields);
144+
Map<Integer, String> headerMap = this.getHeaderNames(sheet, fields);
150145

151146
/* Converting cells to objects */
152147
List<Object> resultList = new ArrayList<>();
153-
for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
154-
Row row = sheet.getRow(i);
155-
if (row == null) {
148+
for (Row row : sheet) {
149+
if (row == null || row.getRowNum() == 0) {
156150
continue;
157151
}
158152

159-
Object obj = convertCellValuesToObject(clazz, row, fields, headerMap);
153+
Object obj = this.convertCellValuesToObject(clazz, row, fields, headerMap);
160154
resultList.add(obj);
161155
}
162156

@@ -166,19 +160,21 @@ public List<?> excelToObjects(File file, Class<?> clazz, String sheetName) throw
166160
return resultList;
167161
}
168162

169-
private Map<Integer, String> getHeaderNames(Sheet sheet, Field[] fields) {
163+
private Map<Integer, String> getHeaderNames(Sheet sheet, Field[] fields) throws HeaderNotPresentException {
170164
Map<String, String> fieldNames = new HashMap<>();
171165
for (Field field : fields) {
172166
ExcelField excelField = field.getAnnotation(ExcelField.class);
173167
fieldNames.put(excelField == null ? field.getName() : excelField.name(), field.getName());
174168
}
175169

176170
Row headerRow = sheet.getRow(0);
171+
if (headerRow == null)
172+
throw new HeaderNotPresentException("There is no header in the first row of the sheet.");
173+
177174
Map<Integer, String> headerMap = new TreeMap<>();
178-
for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) {
179-
Cell cell = headerRow.getCell(i);
175+
for (Cell cell : headerRow) {
180176
if (fieldNames.containsKey(cell.getStringCellValue())) {
181-
headerMap.put(i, fieldNames.get(cell.getStringCellValue()));
177+
headerMap.put(cell.getColumnIndex(), fieldNames.get(cell.getStringCellValue()));
182178
}
183179
}
184180

@@ -187,9 +183,13 @@ private Map<Integer, String> getHeaderNames(Sheet sheet, Field[] fields) {
187183

188184
private Object convertCellValuesToObject(Class<?> clazz, Row row, Field[] fields, Map<Integer, String> headerMap) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException {
189185
Object obj = clazz.getDeclaredConstructor().newInstance();
190-
for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
191-
String headerName = headerMap.get(j);
192-
Cell cell = row.getCell(j);
186+
for (Cell cell : row) {
187+
if (cell == null)
188+
continue;
189+
190+
String headerName = headerMap.get(cell.getColumnIndex());
191+
if (headerName == null || headerMap.isEmpty())
192+
continue;
193193

194194
switch (cell.getCellType()) {
195195
case NUMERIC -> {
@@ -243,7 +243,7 @@ private CellStyle createHeaderCellStyle(Workbook workbook, Class<?> clazz) {
243243
if (excelHeaderStyle == null) {
244244
return cellStyle;
245245
}
246-
return createCellStyle(cellStyle, excelHeaderStyle.cellColor(), excelHeaderStyle.horizontal(), excelHeaderStyle.vertical());
246+
return this.createCellStyle(cellStyle, excelHeaderStyle.cellColor(), excelHeaderStyle.horizontal(), excelHeaderStyle.vertical());
247247
}
248248

249249
private void writeExcelBody(Workbook workbook, Sheet sheet, Field[] fields, Object object, int cRow, CellStyle cellStyle, Class<?> clazz) throws IllegalAccessException {
@@ -285,7 +285,7 @@ private void writeExcelBody(Workbook workbook, Sheet sheet, Field[] fields, Obje
285285
}
286286

287287
/* Set auto-size columns */
288-
setAutoSizeColumn(sheet, fields, clazz);
288+
this.setAutoSizeColumn(sheet, fields, clazz);
289289
}
290290

291291
private CellStyle createBodyStyle(Workbook workbook, Class<?> clazz) {
@@ -294,7 +294,7 @@ private CellStyle createBodyStyle(Workbook workbook, Class<?> clazz) {
294294
if (excelBodyStyle == null) {
295295
return cellStyle;
296296
}
297-
return createCellStyle(cellStyle, excelBodyStyle.cellColor(), excelBodyStyle.horizontal(), excelBodyStyle.vertical());
297+
return this.createCellStyle(cellStyle, excelBodyStyle.cellColor(), excelBodyStyle.horizontal(), excelBodyStyle.vertical());
298298
}
299299

300300
private CellStyle createCellStyle(CellStyle cellStyle, IndexedColors indexedColors, HorizontalAlignment horizontal, VerticalAlignment vertical) {
@@ -324,20 +324,10 @@ private void setAutoSizeColumn(Sheet sheet, Field[] fields, Class<?> clazz) {
324324

325325
private String getPathname(String path, String filename, ExcelExtension extension) {
326326
path = path.replaceAll("\\\\", "/");
327-
if(path.charAt(path.length() - 1) != '/') {
327+
if (path.charAt(path.length() - 1) != '/') {
328328
path += '/';
329329
}
330330

331331
return path + filename + '.' + extension.getExt();
332332
}
333-
334-
private String checkExtension(String filename) throws ExtensionNotValidException {
335-
String extension = FilenameUtils.getExtension(filename);
336-
ExcelUtils excelUtils = new ExcelUtilsImpl();
337-
338-
if(!excelUtils.isValidExcelExtension(extension)) {
339-
throw new ExtensionNotValidException("Pass a file with the XLS or XLSX extension");
340-
}
341-
return extension;
342-
}
343333
}

0 commit comments

Comments
 (0)