dev.spiti.utility.datareader.readers.Excel Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of data-reader Show documentation
Show all versions of data-reader Show documentation
A utility to read test data from excel and csv and write data as needed
The newest version!
package dev.spiti.utility.datareader.readers;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
public class Excel extends BaseReader {
private XSSFWorkbook book;
private XSSFSheet sheet;
private XSSFRow row;
private XSSFCell cell;
private static final String EXTENSION = ".xlsx";
public Excel() {}
public Excel(String file, String sheetName) {
this.sheet = readFile(file, sheetName);
}
/**
* Reads the sheet from a defined file and returns the sheet as an instance of XSSFSheet
* @param file - absolute path of the file, including file name
* @param sheetName - name of the sheet to be read
* @return Sheet as an instance of XSSFSheet
*/
public XSSFSheet readFile(String file, String sheetName) {
XSSFWorkbook workbook = readFile(file);
return sheet = workbook.getSheet(sheetName);
}
public XSSFWorkbook readFile(String file) {
try{
FileInputStream excelFile = new FileInputStream(new File(getPath() + file + EXTENSION));
book = new XSSFWorkbook(excelFile);
}catch (Exception ex){
LOGGER.error("Error is reading excel file " + ex.getMessage());
}
return book;
}
/**
* Returns number of rows exist in the sheet
* @param sheet Sheet to be read, as an instance of XSSFSheet
* @return number of rows in the sheet
*/
public int getRowCount(XSSFSheet sheet){
return sheet.getLastRowNum();
}
/**
* Returns the given row as an instance of XSSFRow
* @param sheet Sheet name to be read from
* @param rowNum row umber to be read
* @return Data on the row as an instance of XSSFRow
*/
public XSSFRow readRow(XSSFSheet sheet, int rowNum){
return sheet.getRow(rowNum);
}
/**
* Returns number of columns exist in the sheet
* @param row row to be read for number of columns, as an instance of XSSFRow
* @return number of columns in the row
*/
public int getColumnCount(XSSFRow row){
return row.getPhysicalNumberOfCells();
}
/**
* Returns data in the given row, as an instance of XSSFRow, in an ArrayList
* @param row row to be read, as an instance of XSSFRow
* @return All the data in row as elements in ArrayList
*/
public ArrayList