@Component
public class ExcelUtils {
private XSSFWorkbook excelWBook;
private FileInputStream excelFile = null;
public void init(String path) {
try {
System.out.println("Open: " + path);
excelFile = new FileInputStream(path);
// Access the required test data sheet
excelWBook = new XSSFWorkbook(excelFile);
} catch (FileNotFoundException e) {
System.out.println("Could not read the Excel sheet");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Could not read the Excel sheet");
e.printStackTrace();
}
}
public void shutdown() {
try {
System.out.println("Attempt to close Excel sheet");
excelFile.close();
} catch (IOException e) {
System.out.println("Could not close the Excel sheet");
e.printStackTrace();
}
}
public Object[][] getExcelSheetAsMatrix(ExcelSheetProperties excelProps) throws Exception {
String[][] mat = null;
XSSFSheet excelWSheet = excelWBook.getSheet(excelProps.getSheetName());
int startRow = excelProps.getFirstRow() - 1;
int startCol = excelProps.getFirstColumn() - 1;
int totalRows = excelProps.getLastRow() - 1;
int totalCols = excelProps.getLastColumn() - 1;
mat = new String[totalRows][totalCols + 1];
int ci = 0, cj = 0;
for (int i = startRow; i <= totalRows; i++, ci++) {
cj = 0;
for (int j = startCol; j <= totalCols; j++, cj++) {
mat[ci][cj] = getCellData(i, j, excelWSheet);
}
}
return mat;
}
private String getCellData(int rowNum, int colNum, XSSFSheet excelWSheet) throws Exception {
XSSFCell cell;
try {
cell = excelWSheet.getRow(rowNum).getCell(colNum);
if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
return "";
}
return cell.getStringCellValue();
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
}
}