Reputation: 35
I want to set the excel data to a Java POJO
My Excel will be
firstName lastName amount
A B E
C D F
I have created the Java Bean which exactly matches with the excel Headers
public class ExcelBean {
private String firstName;
private String lastName;
private String amount;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
The below code performs the excel row. It iterates through each and every column and get the cell data
static File file;
static FileInputStream fileInputStream;
static XSSFWorkbook workBook;
static XSSFSheet sheet;
static XSSFRow row;
static XSSFCell cell;
static int rowNum;
static int j;
private static final String filePath = "Excel.xlsx";
public static XSSFSheet getSheet() throws IOException {
try {
file = new File(filePath);
fileInputStream = new FileInputStream(file);
workBook = new XSSFWorkbook(fileInputStream);
sheet = workBook.getSheetAt(0);
} catch (Exception e) {
System.out.println("Error while trying to get the sheet " + e.getMessage());
}
return sheet;
}
public static void getExcelData(XSSFSheet sheet) {
int totalRows = sheet.getLastRowNum()+1;
int totalColums = sheet.getRow(0).getLastCellNum();
ExcelBean excelBean=new ExcelBean();
for(int i=0;i<totalRows;i++){
row=sheet.getRow(i);
for(int j=0;j<totalColums;j++){
String fieldValue = row.getCell(j).getStringCellValue();
System.out.println(fieldValue);
}
}
}
public static void main(String[] args) throws IOException{
sheet=ExcelUtil.getSheet();
ExcelUtil.getExcelData(sheet);
}
My intention is to get the value from the excel and set it to the java bean which I am not aware of. Can any one help me achieving this functionality.
Upvotes: 1
Views: 2520
Reputation: 1266
Update getExcelData() function like this
public static void getExcelData(XSSFSheet sheet) {
int totalRows = sheet.getLastRowNum()+1;
int totalColums = sheet.getRow(0).getLastCellNum();
ExcelBean excelBean=new ExcelBean();
for(int i=0;i<totalRows;i++){
row=sheet.getRow(i);
for(int j=0;j<totalColums;j++){
String fieldValue = row.getCell(j).getStringCellValue();
System.out.println(fieldValue);
switch(j)
{
case 0:excelBean.setFirstName(fieldValue);break;
case 1:excelBean.setLastName(fieldValue);break;
case 2:excelBean.setAmount(fieldValue);break;
default:break;
}
}
}
}
Upvotes: 2