Excel is missing some values while writing - java

I am new to Apache-poi and using 3.8 version of poi. While writing value in the Excel,i check for the column names if they matched, i will write some value in that column and finish it, and again i will start writing on header. The problem is if write three column values only last column values are add or saved and first two values are not saved in the column. Can anyone tell what went wrong.
(sorry, in case any mistake)
Code:
int i = 0;
Row row = sheet.createRow(i);
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_ORANGE.index);
String validate_header = null;
while (iterator.hasNext()) {
if (eiterator.hasNext()) {
validate_header = eiterator.next();
}
Cell cell = row.createCell(i);
String col_heading = iterator.next();
cell.setCellValue(col_heading);
if(col_heading.equalsIgnoreCase("Assigned Date"))
{
Add_value(i, col_heading, row, sheet);
row=sheet.getRow(0);
cell=row.getCell(i);
}
else if(col_heading.startsWith("Review"))
{
int count=-1;
int n=Col_values.get("Defect Summary").size();
for (int j = 0; j < n; j++) {
row = sheet.createRow(count);
cell = row.createCell(i);
String s="External QC Defect ";
cell.setCellValue(s);
count++;
}
row=sheet.getRow(0);
cell=row.getCell(i);
}
sheet.autoSizeColumn(i);
i++;
}
private static Sheet Add_value(int k,String name,Row row, Sheet sheet) {
System.out.println("Inside the add method");
if(name.equalsIgnoreCase("Assigned Date")||name.equalsIgnoreCase("Reported Date") )
{
vector = Col_values.get("TargetDate");
int count = 1;
System.out.println("IF Size of the vector " + vector.size());
for (int j = 0; j < vector.size(); j++) {
row = sheet.createRow(count);
cell = row.createCell(k);
String s = (String) vector.get(j);
System.out.println(s);
cell.setCellValue(s);
count++;
}
}
else
{
vector = Col_values.get("Defect Summary");
int count = 1;
System.out.println("ELSE Size of the vector " + vector.size());
for (int j = 0; j < vector.size(); j++) {
row = sheet.createRow(count);
cell = row.createCell(k);
String s = (String) vector.get(j);
System.out.println(s);
cell.setCellValue(s);
count++;
}
}
return sheet;
}
'
Can u tell what went Wrong?

It seems that Add_value starts creating rows from top. Therefore on the second call the old rows are removed.
Replace
row = sheet.createRow(count);
with
row = k == 0 ? sheet.createRow(count) : sheet.getRow(count);

Related

Reading 2D double array in Excel Using Apache POI

I am trying to make use of Apache POI to read an excel file and convert it to a 2-dimensional object array. Attached is the code section.
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(1);
int numRows = 3;
int cols = 5;
double[][] excelData = new double[numRows][cols];
for (int i = 1; i < numRows; i++) {
Row row = firstSheet.getRow(i);
if (row != null) {
for (int j = 1; j < cols; j++) {
Cell cell = row.getCell(j);
if (cell != null) {
try {
excelData[i][j] = cell.getNumericCellValue();
} catch (IllegalStateException e) {
System.out.println("Cell data is not a double");
}
}
}
}
}
workbook.close();
inputStream.close();
return excelData;
}
enter image description here This is my excel sheet and I want to "just" read the blue part of it as a 2d array, but after running the code the first row and column all are zero and I don't want it, appreciate your help on how can quickly pull out all the zeros enter image description here.
You need to change index in the 1st loop to 0 (first field in excel file)
but in row you must provide index + 1 bc you need to read from the 2nd field.
Same analogy for 2nd loop and cell field
Workbook workbook = new XSSFWorkbook(new File("d:\\book1.xlsx"));
Sheet firstSheet = workbook.getSheetAt(1);
int numRows = 3;
int cols = 5;
double[][] excelData = new double[numRows][cols];
for (int i = 0; i < numRows; i++) {
Row row = firstSheet.getRow(i + 1);
if (row != null) {
for (int j = 0; j < cols; j++) {
Cell cell = row.getCell(j + 1);
if (cell != null) {
try {
if (cell.getCellType().equals(CellType.NUMERIC)) {
excelData[i][j] = Double.valueOf(cell.getNumericCellValue());
}
} catch (IllegalStateException e) {
System.out.println("Cell data is not a double");
}
}
}
}
}
workbook.close();
Returned result for it:
0.041256 0.033079 -0.01138 -0.02138 -0.01138
0.041256 0.033079 -0.01138 -0.01138 -0.01138
0.020628 0.01654 -0.00569 -0.10569 -0.00569

Align text center in the merged region in excel using apache poi in java

I have created an excel sheet, where I am inserting the value to cell and merging cells vertically at the same time and I am able to achieve that but the problem is that, I am not able to align text vertically center in the merged cell.Currently, text is showing at the bottom of vertically merged cell.
here's my code,
CellStyle cs = null;
cs = wb.createCellStyle();
cs.setWrapText(true);
//cs.setAlignment(CellStyle.ALIGN_CENTER);
cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
cs.setFont(f);
Row row[]=new Row[pageListAcrToDept.size()];
for (int i = 0; i < pageListAcrToDept.size(); i++) {
rowIndex = 8 + i ;
row[i]=sheet.createRow(rowIndex);
}
List<List<String>> datas=new ArrayList<>();
datas.add(pageListAcrToDept);
datas.add(notesListAcrToDept);
datas.add(treatmentListAcrToDept);
datas.add(upcListAcrToDept);
datas.add(itemCodeListAcrToDept);
datas.add(descListAcrToDept);
datas.add(subDeptListAcrToDept);
datas.add(limitListAcrToDept);
datas.add(XforListAcrToDept);
datas.add(priceListAcrToDept);
datas.add(couponListAcrToDept);
datas.add(adzoneListAcrToDept);
datas.add(promoDescListAcrToDept);
for (int column = 0; column < 13; column++) {
List <String> list=datas.get(column);
int index=0;
for (int i = 0, prev = -1; i < list.size(); i++) {
if (i == list.size() - 1 || ! list.get(i).equals(list.get(i + 1))) {
//System.out.printf("number: %d, count: %d%n", list.get(i), i - prev);
for(int pos=0;pos<i - prev;pos++){
int posi=index+pos;
Cell cell= row[posi].createCell(column);
cell.setCellStyle((CellStyle) cs);
cell.setCellValue(list.get(i));
}
int startrowpos=index+8;
int endrowpos=index+8+(i - prev)-1;
if(startrowpos==endrowpos){
LOG.info("don't merge");
}else{
CellRangeAddress cellRangeAddress = new CellRangeAddress(startrowpos, endrowpos,
column, column);
sheet.addMergedRegion(cellRangeAddress);
}
index=index+(i - prev);
prev = i;
}
}
}
Finally, I resolved this problem. I am posting here the changes,because it may help other.
for (int column = 0; column < 13; column++) {
List <String> list=datas.get(column);
int index=0;
for (int i = 0, prev = -1; i < list.size(); i++) {
if (i == list.size() - 1 || ! list.get(i).equals(list.get(i + 1))) {
//System.out.printf("number: %d, count: %d%n", list.get(i), i - prev);
int posi=0;
for(int pos=0;pos<i - prev;pos++){
if(pos==0){
posi=index+pos;
}
}
int startrowpos=index+8;
int endrowpos=index+8+(i - prev)-1;
if(startrowpos==endrowpos){
LOG.info("don't merge");
Cell cell= row[posi].createCell(column);
cell.setCellStyle((CellStyle) cs);
cell.setCellValue(list.get(i));
}else{
CellRangeAddress cellRangeAddress = new CellRangeAddress(startrowpos, endrowpos,
column, column);
sheet.addMergedRegion(cellRangeAddress);
Cell cell= row[posi].createCell(column);
cell.setCellStyle((CellStyle) cs);
cell.setCellValue(list.get(i));
}
index=index+(i - prev);
prev = i;
}
}
}

Read Excel file and skip empty rows but not empty columns

I wish to read an Excel file and skip the empty rows. My code skips empty cells but it skips empty columns, too. How can I skip empty rows but maintain empty columns? I'm using JXL Java.
for (int i = 0; i < sheet.getRows(); i++) {
for (int j = 0; j < sheet.getColumns(); j++) {
Cell cell = sheet.getCell(j, i);
String con = cell.getContents();
if (con != null && con.length() != 0) {
System.out.print(con);
System.out.print("|");
}
else {
continue;
}
}
}
Try this:
for (int i = 0; i < sheet.getRows(); i++) {
boolean rowEmpty = true;
String currentRow = "";
for (int j = 0; j < sheet.getColumns(); j++) {
Cell cell = sheet.getCell(j, i);
String con=cell.getContents();
if(con !=null && con.length()!=0){
rowEmpty = false;
}
currentRow += con + "|";
}
if(!rowEmpty) {
System.out.println(currentRow);
}
}
What you were doing is:
Loop through rows
Loop through columns
Print cell if it's empty only, skip it otherwise (your continue statement does nothing as it's the last instruction in the loop anyway, and a break statement would just stop reading the row once it reaches an empty cell)
What this does is:
Loop through rows
Loop through columns
Append the cell to the row's string, and if it's non-empty then set rowEmpty to false (as it contains at least one non-empty cell)
Print the row only if it's not empty
In case of C#, This works for me
private bool CheckIfEmptyRow(ISheet worksheet, int rowIndex)
{
var worksheetRow = worksheet.GetRow(rowIndex);
bool isRowEmpty = true;
for (var columnIndex = worksheetRow.FirstCellNum; columnIndex < worksheetRow.LastCellNum; columnIndex++)
{
ICell cell = worksheetRow.GetCell(columnIndex, MissingCellPolicy.RETURN_NULL_AND_BLANK);
if (!string.IsNullOrEmpty(cell.StringCellValue))
{
isRowEmpty = false;
break;
}
}
return isRowEmpty;
}

Apache poi how to get cell coordinates

I try to get a cell's coordinates, right now I write next code:
for (Row row : sheet) {
for(Cell cell : row){
// how to get a cell coordinates?
}
}
How can I get a cell's coordinates (dx1, dx2, dy1, dy2) ?
the shortest way to get cell address is:
cell.getAddress().formatAsString()
to get sheet name do the following
cell.getSheet().getSheetName()
The obvious solution was suggested by user2310289, but that won't work as the iterators skip over blank rows and cells.
So, one option is to iterate manually, taking care of blank cells, and then you'll always know where you cell is, with code something like:
// Decide which rows to process
int rowStart = Math.min(15, sheet.getFirstRowNum());
int rowEnd = Math.max(1400, sheet.getLastRowNum());
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
Row r = sheet.getRow(rowNum);
int lastColumn = Math.max(r.getLastCellNum(), MY_MINIMUM_COLUMN_COUNT);
for (int cn = 0; cn < lastColumn; cn++) {
Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null) {
// The spreadsheet is empty in this cell
} else {
// Do something useful with the cell's contents
CellReference cr = new CellReference(c);
System.out.println("Cell at " + rowNum + "," + cn + " found, that's " + cr.formatAsString());
}
}
}
Or, if you do want to use the easy iterators, you need to look up the row and cell index from a cell, eg
for (Row r : sheet) {
for (Cell c : r) {
int columnNumber = c.getColumnIndex();
int rowNumber = c.getRow().getRowNum();
CellReference cr = new CellReference(c);
System.out.println("Cell at " + rowNum + "," + columnNumber + " found, that's " + cr.formatAsString());
}
}
I have done following code for getting coordinates of the excel cell. Hope this will help you.
public static void searchSheet(String searchText, XSSFSheet sheet)
{
int flag=0;
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++)
{
XSSFRow row = sheet.getRow(i);
for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++)
{
XSSFCell cell = row.getCell(j);
String CellData=cell.toString();
if(searchText.equals(CellData))
{
flag=1;
CellData=row.getCell(j+1).toString();
System.out.println(CellData);
System.out.println("String Found At Row="+ i +" and At Column="+j);
}
}
break;
}
if(flag==0)
{
System.out.println("String Not Found");
}
}

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

Categories