Iterator to array Java - java

I'm working on a little app with Java on Netbeans, and I need to export the data of Excel file to an array and then work on this array.
To get the excel I use Apache POI and I can show the value of the excel file in the consol.
However, I need to put it in an array, and for the moment I don't know how to work with the Iterator because I am getting the excel data into an iterator.
Workbook workbook = WorkbookFactory.create(new File(pathConfig1));
//File
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
Sheet sheet = workbook.getSheetAt(nbSheet1);
//Get index sheet user
Iterator<Row> rowIterator = sheet.rowIterator();
int nbLine= sheet.getLastRowNum() +1;
//Number of Lines
int nbCol = sheet.getRow(0).getLastCellNum();
// Number of columns
String [][]data= new String[nbLine][nbCol];
//Array for the data
From this point I don't really know how to export the data in my array...
Any idea ?
I thought to use 2 loop for but I don't know how to increment my Iterator...

As what I've understood, you want to store the every cell values in each row in an array right? If that's the case yes, you're right to use 2 loops and the iterator is optional in this case. I've rewritten your code and hope it helps.
Workbook workbook = WorkbookFactory.create(new File(pathConfig1));
// Iterator<Sheet> sheetIterator = workbook.sheetIterator();
Sheet sheet = workbook.getSheetAt(0);
// Iterator<Row> rowIterator = sheet.rowIterator();
int nbLine = sheet.getLastRowNum() + 1;
int nbCol = sheet.getRow(0).getLastCellNum();
String[][] data = new String[nbLine][nbCol];
for (int i = 0; i < nbLine; i++) {
Row row = sheet.getRow(i);
for (int j = 0; j < nbCol; j++) {
Cell cell = row.getCell(j);
data[i][j] = cell.toString();
}
}
// Display
for (int i = 0; i < nbLine; i++) {
StringBuffer buff = new StringBuffer();
int j = 0;
for (; j < nbCol - 1; j++) {
buff.append(data[i][j]);
buff.append(",");
}
buff.append(data[i][j]);
System.out.println(buff.toString());
}

I'm not familiar with the specific library you're using, but an easy way to use iterators is in a for each loop
Something like
for (Sheet sheet : workbook.sheetIterator()) {
for (Row row : sheet.rowIterator()) {
data[row][col] = //row.getCellValue()? Like I said, I don't know this library
}
}

Related

Get values in every row with specific column name's using POI

I want to read .xlsx file to get values in every row with specific column name's and keep them into string array.
Sample data from file.xlsx
A B C
A123 B123 C123
A456 B456 C456
A789 B789 C789
A999
This is the code that try to get values from column A, but it's not get the correct result.
InputStream is = file.getInputstream();
int rowTotal = 0;
XSSFWorkbook wb = new XSSFWorkbook(is);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row = sheet.getRow(0);
rowTotal = sheet.getLastRowNum();
if((rowTotal > 0) || (sheet.getPhysicalNumberOfRows() > 0)) {
rowTotal++;
log.debug("rowTotal : "+rowTotal);
int colNum = -1;
for(int i = 0; i <= rowTotal; i++) {
if(row.getCell(i).getStringCellValue().trim().equals("A"))
colNum = i;
row = sheet.getRow(i+1);
XSSFCell cellA = row.getCell(colNum);
DataFormatter formatter = new DataFormatter();
String valueA = formatter.formatCellValue(cellA);
log.debug("Data from col A : "+valueA);
}
}
}
The result from log are..
rowTotal : 5
Data from col A : A123
Data from col A : A456
Data from col A : A789
Why it's not print "A999" ?

Is there a way to check excel sheet has rows null in POI java library?

I could not find any method to check POI sheet has null rows.
I have tried, Sheet.getLastRowNum(),Sheet.getFirstRowNum(),Sheet.rowIterator(), they all issue NPE.
I am really really confusing right now.
Note: But Sheet object itself is not null though.
int numberOfSheets = wb.getNumberOfSheets();
Sheet sheet;
int maxColumnsCount = 0, headerRowIndex = 0;
Row row;
Member member;
List<Member> members = new ArrayList<>();
for (int i = 0; i < numberOfSheets; i++) {
sheet = wb.getSheetAt(i);
//find the maximum cells in a row, it is assumed that max cells container is only valid data. Otherwise Header or Footer.
//THISE LINE('sheet.getPhysicalNumberOfRows()') GIVE ME NULL POINTER EXCEPTION.
for (int rowIndex = 0; rowIndex < sheet.getPhysicalNumberOfRows(); rowIndex++) {
row = sheet.getRow(rowIndex);
if (maxColumnsCount < row.getPhysicalNumberOfCells()) {
maxColumnsCount = row.getPhysicalNumberOfCells();
headerRowIndex = rowIndex;
} else {
break;
}
}
for (int rowIndex = 0; rowIndex < sheet.getPhysicalNumberOfRows(); rowIndex++) {
row = sheet.getRow(rowIndex);
if (headerRowIndex < rowIndex) {
member = parseMember(row, memberExcelImportType);
member.getTownship().setId(townshipId);
if (StringUtils.isNotEmpty(member.getFullName()))
members.add(member);
}
}
}
Sorry, here's the stack trace.
java.lang.NullPointerException
at org.apache.poi.xssf.usermodel.XSSFSheet.getPhysicalNumberOfRows(XSSFSheet.java:842)
at com.taraaung.tarabar.tarabarlibs.utility.ImportUtilPOI.readExcelFileUsingPOI(ImportUtilPOI.java:45)
at com.taraaung.tarabar.tarabarlibs.utility.ImportUtils.readExcelFile(ImportUtils.java:32)
at com.taraaung.taraserver.server.personExportImportUrl.PersonExportImportHttpServe.doPersonImport(PersonExportImportHttpServe.java:153)
at com.taraaung.taraserver.server.personExportImportUrl.PersonExportImportHttpServe.serve(PersonExportImportHttpServe.java:86)
at com.taraaung.taraserver.server.MyServer$ValidateSession.serve(MyServer.java:2608)
at com.taraaung.taraserver.server.MyServer.serve(MyServer.java:770)
at com.taraaung.taraserver.server.NanoHTTPD$HTTPSession.execute(NanoHTTPD.java:1557)
at com.taraaung.taraserver.server.NanoHTTPD$ClientHandler.run(NanoHTTPD.java:1152)
at java.lang.Thread.run(Thread.java:745)
Umm, just found that the sheet which issues NPE is ChartSheet (i.e, it does not have any kind of rows), then I just check the instance of sheet and skip chart sheets. :D if (sheet instanceof XSSFChartSheet) {
continue;
}
'Thanks for the help'

How to format the Excel document created by POI

I am working in an application where I am creating an Excel document using POI. The problem is, when generating the Excel without any data is fine, but when I am putting the data with it then the headers are going down. My code:
HSSFWorkbook hwb = null;
hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
HSSFRow rowhead = sheet.createRow((short) largest);
HSSFCell intervieweeName = rowhead.createCell(0);
intervieweeName.setCellValue("Interviee Name");
HSSFCell interviewTiming = rowhead.createCell(1);
interviewTiming.setCellValue("Interview Timing");
for (int large = 0; large < largest; large++) {
int i=0;
HSSFRow array1 = sheet.createRow((short)large);
for ( i = i + large; i < interviewerNameList.size(); i++) {
HSSFCell tracker1 = array1.createCell(0);
HSSFCell tracker2 = array1.createCell(1);
tracker1.setCellValue(interviewerNameList.get(large));
tracker2.setCellValue(interviewTimingToFrom1.get(large));
}
}
The problem is that the heading Interviee Name and Interview Timing are coming after the values.
Your problem is that you're writing the header into the last row
HSSFRow rowhead = sheet.createRow((short) largest);
...
for (int large = 0; large < largest; large++) {
HSSFRow array1 = sheet.createRow((short)large);
That puts the header at the end, and loops from 0 to that to create the data rows
Change it instead to be something like:
HSSFRow rowhead = sheet.createRow(0);
...
for (int large = 0; large < largest; large++) {
HSSFRow array1 = sheet.createRow(large+1);
That way, the large variable remains unchanged for your data lookup, but you populate things in row 1 onwards

How to do cell iteration of excel in java

I am having an excel with 2 rows and 5 columns. Now I entered code manually to take values from 1st row. How can I iterate the process?
Below is the code for 1st row in excel. From the 2nd row on, I dont know how to do... I want to iterate one row after another.
Workbook workbook = Workbook.getWorkbook(new File(
"\\C:\\users\\a-4935\\Desktop\\DataPool_CA.xls"));
Sheet sheet = workbook.getSheet("Sheet1");
System.out.println("Reached to Sheet");
Cell a = sheet.getCell(2,1);
Cell b = sheet.getCell(3,1);
Cell c = sheet.getCell(4,1);
Cell d = sheet.getCell(5,1);
Cell e = sheet.getCell(6,1);
Cell f = sheet.getCell(7,1);
Cell g = sheet.getCell(8,1);
Cell h = sheet.getCell(9,1);
Cell i = sheet.getCell(10,1);
String uId = a.getContents();
String deptFromDat = b.getContents();
String deptToDate = c.getContents();
String dept1 = d.getContents();
String arrival1 = e.getContents();
String eihon1 = f.getContents();
String branchCode1 = g.getContents();
String userType1 = h.getContents();
String sessionId1 = i.getContents();
Use the code below to iterate over all rows of a datasheet:
Sheet sheet = workbook.getSheet("Sheet1");
for (Row row : sheet) {
for (Cell cell : row) {
//your logic
}
}
Or, alternatively, use the following code:
Sheet sheet = workbook.getSheet("Sheet1");
for (int i = 0; i < 2; i++) {
Row row = sheet.getRow(i);
if(row == null) {
//do something with an empty row
continue;
}
for (int j = 0; j < 5; j++) {
Cell cell = row.getCell(j);
if(cell == null) {
//do something with an empty cell
continue;
}
//your logic
}
}
for (int i = 0; i <= sheet.getLastRowNum (); ++i) {
row=(Row) sheet.getRow(i);
Iterator<Cell> cells = row.cellIterator();
while (cells.hasNext())
{ .....
you can use the above code to iterate all rows and all cells
You just need to change 1 to the row number, and use a for loop.
Based on your code you could do the following e.g.
For exmaple:
for(int i=0; i<number; i++)
{
Cell a = sheet.getCell(2,i);
Cell b = sheet.getCell(3,i);
Cell c = sheet.getCell(4,i);
...
}
Or better yet move the Cell declarations out of the for loop which is better practice.
Cell a,b, c...;
for(int i=0; i<number; i++)
{
a = sheet.getCell(2,i);
b = sheet.getCell(3,i);
c = sheet.getCell(4,i);
...
}

excel poi: apply foreground color to blank cells

I want to use poi to set all cells of my excel file to a certain color. however, i keep on getting a nullpointer exception for blank cells. This is what i have so far:
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFCellStyle whiteFG = workBook.createCellStyle();
whiteFG.setFillForegroundColor(HSSFColor.AQUA.index);
whiteFG.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//each row has 20 columns
int numColumns = 20;
for (int colNum = 0 ; colNum < numColumns ; colNum++){
HSSFCell cell = row.getCell((short)colNum);
if (cell != null){
cell.setCellStyle(whiteFG);
}
else if ( "".equals(cell.getStringCellValue()) ){
cell.setCellStyle(whiteFG);
}
else () {
cell.setCellStyle(whiteFG);
}
any advice on how i can color the blank cells?
Your code can not even compile.
But the reason you getting a NullPointerException, is because this code
if (cell != null){
cell.setCellStyle(whiteFG);
}
else if ( "".equals(cell.getStringCellValue()) ){
cell.setCellStyle(whiteFG);
}
All non-null cell will enter the first condition, so the only cell that enter the second condition is null.
*UPDATE : answer the comment *
I assume you want to create a new xls file with colored cell. However, your code miss a point - A new created Workbook dose not contains any sheet/row/cell, you have to create one by yourself.
Here is an example I wrote.
HSSFWorkbook workBook = new HSSFWorkbook();
HSSFCellStyle style = workBook.createCellStyle();
style.setFillForegroundColor(HSSFColor.BROWN.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
HSSFSheet sheet = workBook.createSheet();
int numRow = 20;
int numCol = 20;
for (int rowIndex = 0; rowIndex < numRow; rowIndex++) {
HSSFRow row = sheet.createRow(rowIndex);
for (int colIndex = 0; colIndex < numCol; colIndex++) {
HSSFCell cell = row.createCell(colIndex);
cell.setCellStyle(brownBG);
}
}
FileOutputStream fos = new FileOutputStream("test.xls");
workBook.write(fos);
fos.flush();
fos.close();
System.out.println("done");
The code you wrote use getCell(index) to retrieve cells from a row, this method will only return a null when a you're editing a new xls file.

Categories