How to swap up columns in a xlsx file in apache POI - java

I am working in a xlsx file , where i have to just append the values in the lower row to the upper row.Also i have to skip that row from the output file.First i am giving the excel file screen
I have to append the values below the row Name6 i.e in the header there will be Name1,Name2,Name3....... Name6admin|Name6loc, Name7.
For now the since the cells are merged cell poi is giving the output as Part of a merged cell after Name6.i.e Name6|part of a merged cell that way .I want to modify that as i mentioned.
Now my code is working like I will have All the rows starting from Name1 to Name7 and all the below values they hold.And the thing is i am generating the output in a text file which can not contain the row below Name1,Name2,...etc.But i also have to append values from that . I am givinf my code
#Override
public List<String> processSheet(Sheet sheet) {
ActivityLauncher.logConsoleMsg("Processing sheet " + sheet.getSheetName() + " started");
List<String> rows = new ArrayList<String>();
Iterator<Row> rowIterator = sheet.iterator();
final int startCell=0;
while (rowIterator.hasNext()) {
Row currentRow = rowIterator.next();
StringBuilder row = new StringBuilder();
for (int i = 0; i < currentRow.getLastCellNum(); i++) {
//skipping the rows which i can not contains in the output
if(currentRow.getRowNum()==0 || currentRow.getRowNum()==1|| currentRow.getRowNum()==2|| currentRow.getRowNum()==3|| currentRow.getRowNum()==4|| currentRow.getRowNum()==5|| currentRow.getRowNum()==6|| currentRow.getRowNum()==7|| currentRow.getRowNum()==9|| currentRow.getRowNum()==10|| currentRow.getRowNum()==11) {
continue;
}
//removing the last three rows containing total
if (currentRow.getLastCellNum() < 0 || currentRow.getCell(startCell) == null || "".equals(currentRow.getCell(startCell).getStringCellValue()) || (currentRow.getCell(startCell).getStringCellValue() != null && currentRow.getCell(startCell).getStringCellValue().contains("Total"))) {
continue;
}
else {
Cell currentCell = currentRow.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
String cellValue = excelManager.evalCell(currentCell);
if (!cellValue.isEmpty()) {
row.append(cellValue);
}
//adjusting the cell values with the | or BLANK
if(currentCell == null || currentCell.getCellType() == Cell.CELL_TYPE_BLANK) {
row.append("");
}else {
row.append(SEPARATOR);
}
}
}
if (!row.toString().isEmpty()) {
rows.add(row.toString());
}
}
ActivityLauncher.logConsoleMsg("Processing sheet " + sheet.getSheetName() + " completed");
return rows;
}

Related

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.

Unable to delete particular rows and empty string rows in xlsx spreadsheet using Apache POI

I have this spreadsheet
I would like to iterate all the rows containing "USED" keywords and empty strings (spaces) , save all row numbers that match those criteria to an ArrayList , then loop my spreadsheet and remove all the row numbers listed in my ArrayList.
I tried and modified some solutions from Stackoverflow (one of them from here) . My codes look like this
// Remove "USED" and empty string from spreadsheet
private static void cleanUpSheet(String sheetName, String pathToExcel) throws IOException, InvalidFormatException {
FileInputStream fileInput = new FileInputStream(pathToExcel);
Workbook workbook = WorkbookFactory.create(fileInput);
List<Integer> toRemove = new ArrayList<>();
int index = workbook.getSheetIndex(sheetName);
if (index == -1)
System.out.println("No sheet Found");
else {
System.out.println("Index " + index);
Sheet sheet = workbook.getSheetAt(index);
Iterator<Row> rowItr = sheet.iterator();
DataFormatter formatter = new DataFormatter();
System.out.println("Total ROW " + sheet.getLastRowNum());
while (rowItr.hasNext()) {
Row row = rowItr.next();
if (containsValue(row, row.getFirstCellNum(), row.getLastCellNum())) {
//Row contains value
System.out.println("Value Cell 0 " + formatter.formatCellValue(row.getCell(0)));
if (formatter.formatCellValue(row.getCell(0)).equals("USED")) {
System.out.println("Value cell 0 should contain USED " + formatter.formatCellValue(row.getCell(0)));
toRemove.add(row.getRowNum());
System.out.println("What I am removing "+ row.getCell(4).getRichStringCellValue());
}
continue;
} else {
//Row does not contain value
System.out.println("Empty row " + formatter.formatCellValue(row.getCell(0)));
toRemove.add(row.getRowNum());
System.out.println("What I am removing "+ row.getCell(4).getRichStringCellValue());
}
}
for (int i = 0 ; i<toRemove.size() ; i++) {
System.out.println("To Remove " + toRemove.get(i));
removeRow(pathToExcel,toRemove.get(i),false,sheet);
}
System.out.println("New Total Row " + sheet.getLastRowNum());
}
fileInput.close();
FileOutputStream outFile = new FileOutputStream(new File(pathToExcel));
workbook.write(outFile);
outFile.close();
}
private static void removeRow(String pathToExcel, int rowToBeRemoved, boolean removeIndexOneOnly, Sheet sheet) throws IOException, InvalidFormatException {
if (removeIndexOneOnly == true) rowToBeRemoved = 1;
int lastRowNum = sheet.getLastRowNum();
Row row = sheet.getRow(rowToBeRemoved);
if (row != null && rowToBeRemoved != lastRowNum) {
//System.out.println(row.getCell(3).getRichStringCellValue()); //For Testing
//System.out.println(row.getCell(4).getRichStringCellValue()); //For Testing
System.out.println("row to be removed " + rowToBeRemoved);
System.out.println("last row " + lastRowNum);
sheet.removeRow(row);
sheet.shiftRows(rowToBeRemoved + 1, lastRowNum, -1);
}
if (rowToBeRemoved == lastRowNum) {
System.out.println("Very Last Row");
Row removingRow = sheet.getRow(rowToBeRemoved);
if (removingRow != null) {
sheet.removeRow(removingRow);
}
}
}
The result looks like this
When I run in debug mode , I can see that my List<Integer> toRemove does list the correct row numbers I want to remove (i.e. containing "USED" and empty spaces). So far so good.
But when I execute this part of codes
for (int i = 0 ; i<toRemove.size() ; i++) {
System.out.println("To Remove " + toRemove.get(i));
removeRow(pathToExcel,toRemove.get(i),false,sheet);
}
It just doesn't remove all rows listed in List<Integer> toRemove.
I am using POI 3.17.
I am wondering where could I do wrongly.
Thanks.

How to get column values from an excel using only column name?

I want to read a set of usernames and password from an excel sheet. My user name is present in the First column but my password values are present in the 8th column. I don't want to read the 8th column values by giving the 8th column address. Instead i want to read the password values wherever I place it in the excel sheet. Is there any way to do this ?
FileInputStream fs = new FileInputStream(strReadFile);
Workbook wb = Workbook.getWorkbook(fs);
Sheet sh = wb.getSheet("Sheet1");
int rowCount=sh.getRows();
System.out.println("No of Rows:"+rowCount);
for(int row=1;row<rowCount;row++) {
String Username = sh.getCell(1,row).getContents();
driver.findElement(By.id("user_name")).sendKeys(Username);
String Password = sh.getCell(2,row).getContents();
driver.findElement(By.id("user_pass")).sendKeys(Password);
driver.findElement(By.id("login_button")).click();
}
There is no inbuilt method As per my understanding. Check below method column for your solution.
for(int row=1;row<rowCount;row++) {
String Username = sh.getCell(column("username column",sh),row).getContents();
driver.findElement(By.id("user_name")).sendKeys(Username);
String Password = sh.getCell(column("password column",sh),row).getContents();
driver.findElement(By.id("user_pass")).sendKeys(Password);
driver.findElement(By.id("login_button")).click();
}
public int column(String columnName, Sheet sheetAt) throws Exception{
Row row = sheetAt.getRow(0);
int col = -1;
for (int i=0; i<row.getLastCellNum(); i++) {
Cell cell = row.getCell(i);
if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
continue;
}
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
String text = cell.getStringCellValue();
if (columnName.equals(text)) {
col = i;
break;
}
}
}
if (col == -1) {
throw new Exception("None of the cells in the first row were Patch");
}
return col;
}

Row row = sheet.getRow(rowNumber) returns java.lang.nullpointer exception even when row exist in Excel sheet. I am using Apache POI [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
EDIT: I am using this code to read rows and columns of an excel sheet.But the line marked with double star throws exception(java.lang.nullpointer exception).Apart from this i also want to convert null columns found in between to blank columns.Please help.
There are 2 loops one for row and inner one for column as obvious. Niehter the row is getting read nor the blank cell issue is getting resolved.
public void read(String filePath) throws NullPointerException {
try {
FileInputStream file = new FileInputStream(new File(filePath));
System.out.println("going to create Workbook object to read excel row wise");// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
System.out.println("going to create object sheet to read excel row wise");
XSSFSheet sheet = workbook.getSheetAt(0); //extracts the first sheet of excel
System.out.println("Running row iterator to read excel row wise");
for (int rowNumber = sheet.getFirstRowNum(); rowNumber <= sheet.getLastRowNum(); rowNumber++) {
if (rowNumber == sheet.getFirstRowNum())// this row was skipped as it was header row.
{
System.out.println("skipping first row");
continue;
}
this.rowconcat = ""; // all values of perticular row will be concatinated in this variable.
this.flag = 0;
if (sheet.getRow(rowNumber) == null) {
System.out.println("row detected null");
} else {
// The row has data
System.out.println("row no inside else==="+rowNumber);
**Row row = sheet.getRow(rowNumber);** //This line here throws null pointer exception.
for (int cellNumber = row.getFirstCellNum(); cellNumber <= row.getLastCellNum(); cellNumber++) {
Cell cell = row.getCell(cellNumber);
if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
this.flag = 1; // set to 1 to indicate blank cell but this also doesn't work
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(" "); //inserting space in cell after converting its type to String.
this.rowconcat = this.rowconcat + cell.getStringCellValue() + "~";
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
this.rowconcat = this.rowconcat + cell.getStringCellValue() + "~";
}
}
}
}
}//try block closure
catch(Exception e){
//autogenerated
}
} // function closure
I recommend JXL library better the appache one, I have worked with it sinc elong time. Its only minor problem is that it works only with xls not xlsx (if no updates have taken place till now!).
Have a small example for that:
File xlsFile;
public void manageData ()
{
Workbook w;
try {
w = Workbook.getWorkbook(xlsFile);
// Get the first sheet
Sheet sheet = w.getSheet(0);
int j = 1;
//Begin from the second row
while (j < sheet.getColumns()) {
//staff
Cell infoCell = sheet.getCell(j, 4);
System.out.println(infoCell.getContents());
}
catch (Exception e)
{
}
}

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