Alex Alex - 1 month ago 7
Java Question

Reading data and inputting it into a new Excel file using Java POI

I am Currently trying to read an excel file in java, modify it and then place it into a new excel file. At the minute im just trying to place the read data straight into a new file. My question is how would you get the content from cell.getContents() straight into the new file

if (!f.exists()){

String FileName = "C:\\Users\\alexp\\Desktop\\New_Export.xls";
WritableWorkbook excel = Workbook.createWorkbook(new File(FileName));
WritableSheet sheet = excel.createSheet("Sheet1", 0);

for (int y = 0; y < page.getRows(); y++){

for (int x = 0; x < page.getColumns(); x++){

Cell cell = page.getCell(x ,y +1);
CellType type = cell.getType();

if(type == CellType.LABEL){

System.out.println(cell.getContents());
Label label1 = new Label();
sheet.addCell(label1);
if(type == CellType.NUMBER){

System.out.println(cell.getContents());
Number num1 = new Number ();
sheet.addCell(num1);

}
}
}

System.out.println(" ");

}


System.out.println("The File Has Successfully Been Created!");

excel.write();
excel.close();

}
else{

System.out.println("File is already created!");

}

Answer

You can read each row of an Excel sheet using apache poi as follows:

HssfRow row = sheet.getRow(rowIndex);
HssfCell cell = row.getCell(columnIndex);
FormulaEvaluator fe = workbook.getCreationHelper().createFormulaEvalator();
CellValue cv = fe.evaluate(cell);

Hope this will help you, I have typed this code from mobile, you may get some syntax error correct them it will work. Have a nice day:-)