Reading and Validating Rows with Aspose JAva - java

I am trying to read and validate a Row with Aspose Cells Java, but I have never used ir before and de documentation is not very clear, it doesn't even show you how to read a Row. Heres what I've done so far:
public static void main(String[] args) {
String dataDir = "C:\\Users\\apoac22836\\Desktop\\";
Workbook wb = new Workbook(dataDir + "Example.xlsm");
Worksheet worksheet = wb.getWorksheets().get("BOM");
int column = 1;
for (int i = 0; i < 40; i++) {
Cell lastCell = worksheet.getCells().endCellInColumn((short) column);
for (int row = 0; row <= lastCell.getRow(); row++) {
Cell cell = worksheet.getCells().get(row, column);
System.out.println(cell.getStringValue());
}
column += 1;
System.out.println("------------------------------------------------");
}
}
I brings the value of the cells by columns.

Well, if you need to efficiently enumerate all the data (non empty values) in a range, rows, cells, you may try to use Range.iterator(), RowCollection.iterator() and Cells.iterator() method to get the iterator for specific range, initialized rows and non empty or initialized cells, see the following sample codes for your reference:
e.g
Sample code:
//Range Iterator.
Workbook book = new Workbook("sample.xlsx");
Worksheet sheet = book.getWorksheets().get(0);
Range range = sheet.getCells().getMaxDisplayRange();//You may also create your desired range (in the worksheet) using, e.g sheet.getCells().createRange("A1", "J11");
Iterator rangeIterator = range.iterator();
while(rangeIterator.hasNext())
{
Cell cell = (Cell)rangeIterator.next();
System.out.println(cell.getName() + " is not empty");
}
//Cells Iterator.
Workbook workbook = new Workbook("Book1.xls");
Worksheet sheet = workbook.getWorksheets().get(0);
Cells cells = sheet.getCells();
//Get the iterator from Cells collection
Iterator cellIterator = cells.iterator();
//Traverse cells in the collection
while (cellIterator.hasNext()) {
Cell cell = (Cell) cellIterator.next();
System.out.println(cell.getName() + " " + cell.getValue());
}
//Rows collection Iterator.
String filePath = "c:\\source.xlsx";
Workbook workbook = new Workbook(filePath);
Worksheet worksheet = workbook.getWorksheets().get(0);
RowCollection rows = worksheet.getCells().getRows();
Object obj = rows.iterator().next();
Iterator<Row> rowIterator = worksheet.getCells().getRows().iterator();
while(rowIterator.hasNext())
{
Row r = rowIterator.next();
Iterator<Cell> cellIterator = r.iterator();
while(cellIterator.hasNext())
{
Cell cell= cellIterator.next();
System.out.println(cell.getStringValue());
}
}
Hope, this helps a bit.
I am working as support developer/Evangelist at Aspose.

Related

How to get cell value from the cell which consists of formula in excel xls file

I am writing java code to read excel file and to create an object from that but one column consists of formula when I read cell formula is coming in value field instead of value
I tried to get from cell index
I tried to get value from iterator(hasnext()) method :
like:
public static void CheckDuplicate(File file) throws Exception {
Set newReordsList = new LinkedHashSet();
LinkedHashMap<String, DataCleansingObject> lhm = new LinkedHashMap<String, DataCleansingObject>();
FileInputStream fis = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet spreadsheet = workbook.getSheetAt(0);
HSSFRow row;
Iterator< Row> rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext()) {
row = (HSSFRow) rowIterator.next();
if(row.getRowNum() == 0) {
continue;
}
DataCleansingObject dataObj = new DataCleansingObject();
Iterator< Cell> cellIterator = row.cellIterator();
String key = "";
if (cellIterator.hasNext()) {
dataObj.setDocType(row.getCell(1).toString());
dataObj.setDocNo(row.getCell(2).toString());
dataObj.setDocVer(Long.parseLong(row.getCell(3).toString()));
dataObj.setDocPart(row.getCell(4).toString());
dataObj.setDocLang(row.getCell(5).toString());
dataObj.setDocRev(row.getCell(6).toString());
dataObj.setDocStatus(row.getCell(7).toString());
dataObj.setDocSD(row.getCell(8).toString());
dataObj.setDocLD(row.getCell(9).toString());
dataObj.setDocChangeNumber(row.getCell(10).toString());
key = row.getCell(1).toString() + "_" + row.getCell(2).toString() + "_" + row.getCell(3).toString() + "_" + row.getCell(4).toString();
}
lhm.put(key, dataObj);
}
fis.close();
copyInExcel(newReordsList);
}
When ever I call below line
Long.parseLong(row.getCell(3).toString())
I need to get long value not formula in that cell

Copying of two different excel sheets to one sheet using Java

Copying of two different excel sheets to one new excel sheet using Java code is resulting in partial output.
This is for Java code running in IntelliJ, using Apache POI.
public static void copySheet(XSSFSheet inputSheet1, XSSFSheet outputSheet, XSSFSheet inputSheet2)
{
int rowCount = inputSheet1.getLastRowNum();
int rc = inputSheet2.getLastRowNum(),rcnt=0,cri =0,l=0;
int currentRowIndex = 0, cell = 0;
if (rowCount > 0) {
Iterator rowIterator = inputSheet1.iterator();
while (rowIterator.hasNext()) {
int currentCellIndex = 0;
Iterator cellIterator;
Row row = (Row) rowIterator.next();
cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
//Creating new Row, Cell and Input value in the newly created sheet.
String cellData = cellIterator.next().toString();
if (currentCellIndex == 0)
outputSheet.createRow(currentRowIndex).createCell(currentCellIndex).setCellValue(cellData);
else
outputSheet.getRow(currentRowIndex).createCell(currentCellIndex).setCellValue(cellData);
currentCellIndex++;
System.out.println("content test2 " + cellData);
System.out.println("current row index " + currentRowIndex);
System.out.println("current cell " + cell);
}
currentRowIndex++;
cell = currentCellIndex;
rcnt = cell;
}
}
cri = 0;
if (rc > 0) {
Iterator rowIterator = inputSheet2.iterator();
while (rowIterator.hasNext()) {
int currentCellIndex2 = 0,cci = rcnt+1;
Iterator cellIterator2;
Row row = (Row) rowIterator.next();
cellIterator2 = row.cellIterator();
while (cellIterator2.hasNext()) {
String cellData = cellIterator2.next().toString();
if (currentCellIndex2 == 0)
outputSheet.createRow(cri).createCell(cci).setCellValue(cellData);
else
outputSheet.getRow(cri).createCell(cci).setCellValue(cellData);
currentCellIndex2 = currentCellIndex2+1;
cci = cci +1;
System.out.println("content "+cellData);
System.out.println("current row index " + cri);
}
cri++;
}
}
}
Expected output :
both the sheets should be copied to the new sheet.
Actual output :
only the second input sheet is copied to the new sheet.
If I try to copy one the first sheet it will be copied. But if I try to copy both only second sheet will be present.
Input_one
Input_two
Output
It looks like you are overwriting output of the first while loop with the output of the second because in one you use currentRowIndex and in the second you use cri. Reuse the currentRowIndex for the second while-loop as well, so that the rows from the second sheet get appended after the ones for the first one.

setCellValue not working

i can't set the value of cell ,it works if i try this
if(1==1){
celltofill.setCellValue("test");
}
but once it enters the if condition it displays what's in syso but doesn't insert values in the cell.
any ideas about how can i solve this isssue?
here is my code:
public class testexcel {
public static void main(String[] args) throws InvalidFormatException, IOException, ParseException{
FileInputStream fis = new FileInputStream("D:\\test6.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
FileOutputStream fos=new FileOutputStream("D:\\edit6.xlsx");
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFSheet sheet2 = workbook.getSheetAt(1);
for(int i=1; i <= sheet.getLastRowNum(); i++) {
for(int i1=1;i1<sheet2.getLastRowNum();i1++){
Row row = sheet.getRow(i);
Cell cell = row.getCell(2);
Row row2 = sheet2.getRow(i1);
Cell cell2 = row2.getCell(0);
Cell celltofill= row.createCell(5);
Cell cellres= row2.getCell(1);
if((cell.getStringCellValue()).equals(cell2.getStringCellValue())){
System.out.println((cell.getStringCellValue())+" equals "+cell2.getStringCellValue());
celltofill.setCellType(Cell.CELL_TYPE_STRING);
System.out.println("cell filled with "+cellres.getStringCellValue());
celltofill.setCellValue(cellres.getStringCellValue());
}
}
}
workbook.write(fos);
fos.close();
}
}
row.createCell(5) does exactly what it says. It creates a new empty cell every time it is called. And you are calling it for every row in sheet2 again and again although it is a cell in sheet. So even if the criterions are not fullfilled, the new empty cell is been created already in your code.
Maybe:
...
for(int i=1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
Cell cell = row.getCell(2);
Cell celltofill= row.getCell(5);
if (celltofill == null) celltofill = row.createCell(5);
for(int i1=1;i1<sheet2.getLastRowNum();i1++){
Row row2 = sheet2.getRow(i1);
Cell cell2 = row2.getCell(0);
Cell cellres= row2.getCell(1);
...
will be more what you want?

Check if row contains word

I have a spreadsheet and I only want to select rows that have a specific word in one column and another word in another column. At the moment I am only able to check for the word in any cell in the row. How can I check for the presence of the word in a cell in a specific column?
Here is my code
FileInputStream fis = new FileInputStream(new File(filepath));
XSSFWorkbook workBook = new XSSFWorkbook (fis);
XSSFSheet sheet = workBook.getSheetAt (0);
List<XSSFRow> filteredRows = new ArrayList<XSSFRow>();
Iterator<Row> rows= sheet.rowIterator();
while (rows.hasNext ()){
XSSFRow row = (XSSFRow) rows.next ();
Iterator<Cell> cells = row.cellIterator ();
while (cells.hasNext ()){
XSSFCell cell = (XSSFCell) cells.next ();
if (cell.toString().contains("Ginko")) {
filteredRows.add(row);
break;
}
}
}
You can check if a cell is in a specific column by calling cell.getColumnIndex() == columnNumber. For example:
for(Cell cell : row) {
if(cell.getColumnIndex() == 1) {
// process a cell in column 1
}
}
Source: https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#getColumnIndex()

Get exact last filled row number in an excel file that has is associated with a complex formula using Apache POI

A complex formula is applied to a column till end of the excel sheet.but when I'm retrieving the last row number using Sheet.getLastRowNum()
it is returning last row of the sheet though the excel sheet is having only 10 rows.Is there any way get the exact last filled row in the excel file even if
formula applied to end of the excel sheet?
From http://affy.blogspot.cz/2004/04/poi-optimization-eliminating-trailing.html
Retrieve required formula then use this code. it will remove all those empty rows and then you can get required data with your data retrieving code.
List yourlist = new ArrayList();
String value = null;
FileInputStream inputStreams1 = null;
inputStreams1 = new FileInputStream(FileNameWithPath);
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(inputStreams1);
HSSFSheet sheet = (HSSFSheet) workbook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
boolean stop = false;
boolean nonBlankRowFound;
short c;
HSSFRow lastRow = null;
HSSFCell cell = null;
HSSFRow FirsttRow = null;
while (stop == false) {
nonBlankRowFound = false;
lastRow = (HSSFRow) sheet.getRow(sheet.getLastRowNum());
for (c = lastRow.getFirstCellNum(); c <= lastRow.getLastCellNum(); c++) {
cell = lastRow.getCell(c);
if (cell != null && lastRow.getCell(c).getCellType() != HSSFCell.CELL_TYPE_BLANK) {
nonBlankRowFound = true;
}
}
if (nonBlankRowFound == true) {
stop = true;
yourlist = yourMethod(FileNameWithPath, sheet); //updated HSSFSheet object which will have 10 rows
/*use this code to remove all those empty rows then use hsheet object. now use this hsheet object will
have only non empty rows(in your case 10 rows)*/
} else {
sheet.removeRow(lastRow);
}
}

Categories