How to delete, not clear row in Sheet? - java

I don't know how to delete row without leaving an empty row.
I am using Apache POI 3.9 and I am getting an error using the following code:
public List<MeterInfo> addToList(String patternt) throws ParseException, IOException {
List<Object> data = new ArrayList<Object>();
int lastRowNum = sheet.getLastRowNum();
Row row;
for(int i = 0; i < lastRowNum; i++){
row = sheet.getRow(i);
if(patternt.equals(getCurrentString(row))){
data.add(getDataFromRow(row));
sheet.removeRow(row);
sheet.shiftRows(row.getRowNum() + 1, row.getRowNum() + 1, -1);
}
}
saveWorkbook(new File("blabla.xlsx"));
return data;
}
I've found a solution in https://stackoverflow.com/a/3554129/6812826, but I am getting a NullPointerException because I am decreasing lastRowNum by each deleted row.
Here is the new version:
public List<Object> addToList(String pattern) throws ParseException, IOException {
List<Object> data= new ArrayList<Object>();
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (pattern.equals(getCurrentString(row))) {
data.add(getMeterInfo(row));
deleteRow(row);
}
}
saveWorkbook(new File("blabla.xlsx"));
return data;
}
private void deleteRow(Row row) {
int lastRowNum = sheet.getLastRowNum();
int rowIndex = row.getRowNum();
if(rowIndex >= 0 && rowIndex < lastRowNum){
sheet.shiftRows(rowIndex + 1, lastRowNum, -1);
}
if(rowIndex == lastRowNum){
Row removingRow = sheet.getRow(rowIndex);
if(removingRow != null){
sheet.removeRow(removingRow);
}
}
}

Try this code, it should work:
for(int i = 0; i < sheet.getLastRowNum(); i++)
{
row = sheet.getRow(i);
if(patternt.equals(getCurrentString(row)))
{
data.add(getDataFromRow(row));
// sheet.removeRow(row); NO NEED FOR THIS LINE
sheet.shiftRows(row.getRowNum() + 1, sheet.getLastRowNum() + 1, -1);
i--;
}
}
You need to decrease i by one every time you delete one row. And get the last row number again by using getLastRowNum().

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

java.lang.UnsupportedOperationException: null

I am trying to delete empty cell in apache-poi. I get this error at
unmarkedColumns.remove(unmarkedColumns.get(i)):
There is a problem with remove method.
I don't understand why.Can you help me?
java.lang.UnsupportedOperationException: null
at java.util.AbstractList.remove(Unknown Source)
at java.util.AbstractList$Itr.remove(Unknown Source)
)
Integer[] integers = new Integer[headers.size()];
Arrays.fill(integers, 0);
List<Integer> unmarkedColumns = Arrays.asList(integers);
for (ScoredFormData scoredFormData : scoredFormDatas) {
Row dataRow = sheet.createRow(++rownum);
List<Object> rowValues = prepareExportRow(scoredFormData, visitManager, parameters,
dynamicDatamanager,
scoreCriteriaDefinitions);
for (int i = 0; i < rowValues.size(); i++) {
if (unmarkedColumns.get(i) != 1 && rowValues.get(i) != null
&& !rowValues.get(i).equals("")) {
unmarkedColumns.set(i, 1);
}
}
populateCells(rowValues, dataRow);
}
for (int i = 0; i < unmarkedColumns.size(); i++) {
if (unmarkedColumns.get(i) == 0) {
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Boolean changed = false;
for (int j = i + 1; j < row.getLastCellNum() + 1; j++) {
Cell oldCell = row.getCell(j - 1);
if (oldCell != null) {
row.removeCell(oldCell);
changed = true;
Cell nextCell = row.getCell(j);
if (nextCell != null) {
Cell newCell = row.createCell(j - 1, nextCell.getCellType());
switch (newCell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN: {
newCell.setCellValue(nextCell.getBooleanCellValue());
break;}}}}
if (changed ) {
unmarkedColumns.remove(unmarkedColumns.get(i));
i = 0;
}
}
Arrays.asList(..) returns a List with a fixed size, so you can't expand or shrink it.
To fix it, you could wrap it in an ArrayList:
List<Integer> unmarkedColumns = new ArrayList<>(Arrays.asList(integers));
Your problem is here
List<Integer> unmarkedColumns = Arrays.asList(integers);
If you use Arrays.asList(...), it returns a fixed size list, therefore you cannot remove elements from it.
You could make a workaround by wrapping it:
List<Integer> list = new ArrayList<Integer>(Arrays.asList(integers));

Apache POI : how to manage getLastRowNum errors

I'm using Apache POI to work on an Excel file.
Most of the time it works fine, but sometimes, getLastRowNum() returns a wrong number which causes a null pointer Exception when I arrive at the end of the file.
I want to be sure everything works fine, even when there is something wrong with getLastRowNum().
for (int i = FIRST_ROW_TO_GET; i < sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
System.out.println(row.getCell(9));
}
I tried to use a if row.equals(null) but it doesn't change anything.
Any idea of what I can do?
You can't call row.equals(null) since row is null in this case. You can do the check this way:
for (int i = FIRST_ROW_TO_GET; i < sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
if (row != null){
System.out.println(row.getCell(9));
}
}
The below method will give the accurate last row number in excel, ignoring the blank cells :
int getRowCount(String sheetName) {
int number = 0;
int index = workbook.getSheetIndex(sheetName);
if (index == -1) {
return 0;
} else {
sheet = workbook.getSheetAt(index);
for(int i = 0; i < sheet.getLastRowNum(); i++) {
if(sheet.getRow(i)==null) {
sheet.shiftRows(i+1, sheet.getLastRowNum(), -1);
i--;
}
number = sheet.getLastRowNum() ;
}
}
return number;
}

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

Excel is missing some values while writing

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

Categories