Need help on,
I have an Excel file
TN FN MN LN Type
MR Test1 t1 Test1 abc
MR Test2 t2 abc
MR t3 Test3 abc
MR Test4 t4 Test4 abc
My requirements are:
read rows from java program
check for invalid rows(if either 2nd or 4th column is null/empty then it will be invalid rows and store this row in list1 )
check for valid rows(if neither 2nd or 4th column is not null/empty then it will be valid rows and store this rows in list2)
1)
FileInputStream file = new FileInputStream("c:\\test.xls");
//Get the workbook instance for XLS file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
FileOutputStream out =
new FileOutputStream(new File("C:\\Users\\IBM_ADMIN\\Desktop\\test.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
2) I am stuck here, how can I get the valid and invalid rows?
Appreciate your help
POI takes a little getting used to. You have to explicitly check to see if the cell is blank or null.
There's a good example here on SO.
Related
I have a folder with 216 xsls files. My logic is to loop throw the folder and read every file, copy the first row of each file and write that row to a new .xsls file.
I want to copy the first row without iterating throw the row and read every cell? for example, if you copy the first line in the .txt file or .csv file.
Also, this is a very slow process. Do you have tips to speed up this process?
public static void listFilesForFolder(final File folder,final File exported, int skipLine) {
try {
for (final File fileEntry : folder.listFiles()) {
String ext = fileEntry.getName().substring(fileEntry.getName().lastIndexOf('.') + 1);
System.out.println("-->> " + fileEntry.getName() + "-->>");
FileInputStream file = new FileInputStream(new File(fileEntry.getPath()));
if (fileEntry.isDirectory()) {
continue;
} else if(ext.equals("xlsx")) {
XSSFWorkbook myWorkBook = new XSSFWorkbook(file);
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIterator = mySheet.iterator();
Row row = rowIterator.next();
row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()){
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
default:
}
}
System.out.println("");
file.close();
}
}
}catch (Exception e){
System.out.println(e.getMessage());
}
}
I found the answer to my question.
You can not copy the whole row. You need to loop and read cell by cell.
The solution is:
Declare rowInrecmenter, colIncremnter, xssfWorkbook = new XSSFWorkbook();,
XSSFSheet createdSheet = xssfWorkbook.createSheet("Put any name here");
The variables above need to be outside the loop.
The rest of the codes are:
XSSFRow rowCreated = createdSheet.createRow((short)incr);
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
rowCreated.createCell(col).setCellValue(cell.getStringCellValue());
col++;
break;
case NUMERIC:
rowCreated.createCell(col).setCellValue(cell.getNumericCellValue());
col++;
break;
default:
}
}
xssfWorkbook.write(fileOut);
incr++;
col = 0;
workbook.close();
file.close();
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}finally {
fileOut.close();
xssfWorkbook.close();
}
This is method for reading excel:
#SuppressWarnings("deprecation")
public static void readFromExcel(String file) throws IOException {
workbook = new XSSFWorkbook(file);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
evaluator.evaluateAll();
XSSFSheet myExcelSheet = workbook.getSheetAt(2);
Iterator<Row> itr = myExcelSheet.iterator();
while (itr.hasNext()) {
Row row = itr.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA:
System.out.print("formula:" + cell.getCellFormula() + "\t\t\t");
String value = evaluator.evaluate(cell).getStringValue();
System.out.print(value + "\t\t\t");
break;
case HSSFCell.CELL_TYPE_NUMERIC: // field that represents
// numeric cell type
// getting the value of the cell as a number
System.out.print(cell.getDateCellValue() + "\t\t\t");
break;
case HSSFCell.CELL_TYPE_STRING: // field that represents string
// cell type
// getting the value of the cell as a string
System.out.print(cell.getStringCellValue() + "\t\t\t");
break;
}
}
System.out.println();
}
}
I'm getting below output:
Date ME Balance
formula:'Tab1'!C1 null formula:EOMONTH(A2,0) null formula:'Tab1'!$D$3*1000 null
it's reading formula of the cell but not value.I have tried all methods for FormulaEvaluator. Can anyone please assist on this? I have attached the sample sheet image.SampleScenario.xlsx Tab1.xlsx Tab2.xlsx
When I tried to select items from the item list using Excel sheet through Java environment, only the first item is selected and executed. The next set of iteration is not happening.
int i=1;
while (i<=sheet.getLastRowNum() )
{
row = sheet.getRow(i);
String w = row.getCell(0).getStringCellValue();
// Processing : logic on "items" from excel
i++;
}
OK then try this sample firstly before your code. Check every column and row is visited. Maybe better way is using Iterators.
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
FileOutputStream out =
new FileOutputStream(new File("C:\\test.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I have a column (B) that I need to take all the values between B3 and B20
this is my code
try {
OPCPackage fs;
fs = OPCPackage.open(new File(getFilePath()));
XSSFWorkbook wb = new XSSFWorkbook(fs);
XSSFSheet sheet = wb.getSheet("Master column name - Used Car");
XSSFRow row;
CellReference cr = new CellReference("B3");
row = sheet.getRow(4);
System.out.println(row);
but as you see, i am getting one value, i didn't know how to get the values for cells B3 until B20
could you help please
have you tried replacing this line:
CellReference cr = new CellReference("B3");
with:
AreaReference ar = new AreaReference("B3:B20");
i.e.
AreaReference ar = new AreaReference("B3:B20");
for (cr : ar.getAllReferencedCells()) {
System.out.print(cr.formatAsString());
System.out.print(" - ");
}
System.out.println();
To read values of certain column or cell from excel you might try this
public static void readFromExcel2(){
try{
FileInputStream file = new FileInputStream(new File("java_excel.xlsx"));//place path of your excel file
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(1);//which sheet you want to read
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()){
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()){
Cell cell = cellIterator.next();
if(cell.getColumnIndex()<2&&(cell.getRowIndex()>=3&&cell.getRowIndex()<=20)) {
{
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.print((int) cell.getNumericCellValue()+" \t" );
break;
case Cell.CELL_TYPE_BLANK:
System.out.print(" ");
break;
case Cell.CELL_TYPE_STRING: {
System.out.print(cell.getStringCellValue());
}
}
}
}
}
System.out.println(" ");
}
file.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
I am trying to get a basic java program to read from a xlsx file and put each row into an arrayList as a string, where later on I will then split that String up of that row.
Below is my code, however i'm trying to figure out where I have gone wrong as it doesn't appear to be doing anything.
List<String> text = new ArrayList<String>();
Workbook wb = WorkbookFactory.create(new File("input.xlsx"));
DataFormatter fmt = new DataFormatter();
Sheet s = wb.getSheetAt(0);
for (Row r : s) {
StringBuffer sb = new StringBuffer();
for (Cell c : r) {
if (sb.length() > 0) sb.append(" - ");
sb.append(fmt.formatCell(c));
}
text.append(sb.toString());
}
Any help would be appreciated.
You are not reading any cell. See this example:
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
//..
FileInputStream file = new FileInputStream(new File("C:\\test.xlsx"));
//Get the workbook instance for XLS file
XSSFWorkbook workbook = new XSSFWorkbook (file);
//Get first sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}