Apache POI find last cell in row - java

I have the following code that reads a spreadsheet and writes to pipe-delimeted file. Rows have differing length. The last cell shouldn't get appended with a pipe character (but does). I tried things like https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html#getLastCellNum() but cannot make it work.
XSSFWorkbook wb = new XSSFWorkbook(pathandfilename);
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
XSSFSheet sheet = wb.getSheetAt(i);
String outfilename = path + "\\" + prefix + sheetname + postfix;
PrintWriter outfilewriter = new PrintWriter(outfilename, "UTF-8");
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellType(Cell.CELL_TYPE_STRING);
outfilewriter.print(cell.getStringCellValue() + "|");
}
outfilewriter.print("\n");
}
outfilewriter.close();
}
wb.close();

I fixed it as such:
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<String> recordArry = new ArrayList<String>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellType(Cell.CELL_TYPE_STRING);
recordArry.add(cell.getStringCellValue() + "|");
}
StringBuilder recordString = new StringBuilder();
for (String elem : recordArry) {
recordString.append(elem);
}
String recordString2 = StringUtils.chomp(recordString.toString(), "|");
outfilewriter.print(recordString2);
outfilewriter.print("\n");
}

Related

How do i get row,column coordinates on selected String in excel

how to get row, column coordinate in an excel file?
I'm trying to confirm that user name is in the file. So i try to create a loop that read all the input in the excel file and find the same name as the user name and return the row and column. This is my code.
private int ReadName(String Name){
Iterator<Row> rowIterator = librarianSheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(cell.getCellType() == CellType.STRING){
String random = cell.getRichStringCellValue().getString();
}
if(random == Name){
}
}
}
//return ;
}
But i seems to stuck there because i don't know what to do to get the desirable output. Please help me..
After finding the desired name, return the cell.
private Cell readName(String name){
Iterator<Row> rowIterator = librarianSheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(cell.getCellType() == CellType.STRING){
String random = cell.getStringCellValue();
if(random.equals(name)){
return cell;
}
}
}
}
return null;
}
And then you could use it like this:
Cell cell = readName("Muhammad");
if(cell != null) {
int column = cell.getColumnIndex();
int row = cell.getRowIndex();
}

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

Reading and Validating Rows with Aspose 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.

Covert XLSX row into string and add to array

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();
}

Passing a list of servlet values

Using apache poi, I am reading the first row values of an excel file like this
try
{
FileInputStream file = new FileInputStream(uploadedFile);
XSSFWorkbook workbook = new XSSFWorkbook(file);
for (int i =0; i < workbook.getNumberOfSheets(); i++)
{
XSSFSheet sheet = workbook.getSheetAt(i);
Iterator<Row> rowIterator = sheet.iterator();
String SheetName = "<span class='blue'><b>" +sheet.getSheetName()+ "<b></span><br>";
request.setAttribute("SheetName", SheetName);
Row row = rowIterator.next();
if(row.getRowNum() == 0)
{
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext())
{
Cell cell1 = cellIterator.next();
switch(cell1.getCellType())
{
case Cell.CELL_TYPE_STRING:
String strval = cell1.getStringCellValue();
request.setAttribute("Values2", strval);
break;
}
}
}
}
file.close();
}catch(NoSuchElementException e)
{}
Now, I want to pass a list of values the strval is only sending one value, how do I sent many values??
How to send an array of items to my jsp page?
You can send List as an attribute value. For example:
List<String> cellValues = new ArrayList<String>();
while(cellIterator.hasNext())
{
Cell cell1 = cellIterator.next();
switch(cell1.getCellType())
{
case Cell.CELL_TYPE_STRING:
String strval = cell1.getStringCellValue();
cellValues.add(strval);
break;
}
}
}
}
request.settAttribute("Values2", cellValues);

Categories