I want to remove the cell content but keeping its style but it's always remove the style and content. Here's my code:
private static void RefreshReport(String sheetName, String resultColumn) {
try {
InputStream inp = new FileInputStream(getExcelFile());
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheet(sheetName);
int colResult = getColumnResult(sheet, resultColumn);
int rowStart = getRowResult(sheet, resultColumn);
int rowEnd = Math.max(20, sheet.getLastRowNum());
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
Row r = sheet.getRow(rowNum);
if (r != null) {
Cell cell = r.createCell(colResult);
if (cell.getCellType() != Cell.CELL_TYPE_BLANK) {
CellStyle cs = wb.createCellStyle();
cs = cell.getCellStyle();
r.removeCell(cell);
cell = r.createCell(colResult);
cell.setCellStyle(cs);
}
}
}
FileOutputStream fileOut = new FileOutputStream(getExcelFile());
wb.write(fileOut);
fileOut.close();
inp.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Any help would be great.
The reason that your method isn't working is that you are always calling createCell if the the row r is not null. This will overwrite any Cell that already exists, including contents and styling.
What you need to do is call getCell instead. This will retrieve the Cell at that column index, provided it exists, or null if it doesn't exist. Then if it exists, you can process the Cell as you are doing.
if (r != null) {
Cell cell = r.getCell(colResult);
if (cell != null && cell.getCellType() != CellType.BLANK) {
// rest of your code here
In an alternative to the delete/re-create method you have, you can just set the cell type to BLANK. This will set the contents to blank, but it will also preserve the cell style currently on that cell. There is no need to delete the cell and re-create it.
if (cell.getCellType() != CellType.BLANK) {
cell.setCellType(CellType.BLANK);
}
Related to the rgettman's comment.
But in POI 5.0, you should use cell.setBlank() instead, because cell.setCellType(CellType.BLANK) is deprecated.
Related
I want to write data into excel(.xlsx file) using Apache poi. but getting some error while writing a data. I have followed this video " How to read/write data from Excel file using Apache POI API in Selenium || Latest POI Version", I m able to read data but while writing I m getting this error " Cannot invoke "org.apache.poi.xssf.usermodel.XSSFCell.getStringCellValue()" because the return value of "org.apache.poi.xssf.usermodel.XSSFRow.getCell(int)" is null ", basically nullpointerexception.
enter code here
String resourceGroupNameElement = driver.findElement(By.xpath(FrameworkValidator_Constants.Constants.RESOURCE_GROUP_NAME_XPATH)).getText();
String expectedResult = reader.getCellData("RG",6,2);
if( resourceGroupNameElement== expectedResult) {
String status= "pass";
System.out.println(status);
}
else {
String status="fail";
System.out.println(status);
}
//reader.setCellData("RG", "STATUS/PASS/FAIL", 2, status);
System.out.println(status);
reader.setCellData("RG","ACTUAL RESULT" , 2, resourceGroupNameElement);
Assert.assertEquals(resourceGroupNameElement, expectedResult);
#######
It is showing error in this section
public String setCellData(String sheetName, String colName, int rowNum, String data) {
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
if (rowNum <= 0)
return "";
int index = workbook.getSheetIndex(sheetName);
int colNum = -1;
if (index == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++) {
// System.out.println(row.getCell(i).getStringCellValue().trim());
if (row.getCell(i).getStringCellValue().trim().equals(colName))
colNum = i;
}
if (colNum == -1)
return "";
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum - 1);
if (row == null)
row = sheet.createRow(rowNum - 1);
cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);
// cell style
// CellStyle cs = workbook.createCellStyle();
// cs.setWrapText(true);
// cell.setCellStyle(cs);
cell.setCellValue(data);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return "";
}
return "";
}
so can anybody tell me where I m going wrong.
Have a look at the HOWTO and examples.
You will notice that there are calls for creating a row or creating a cell. Unless you do so, the row/cell does not exist and your getCell() function will return null.
Changing for loop condition part i.e. i < row.getLastCellNum(); to i < row.getLastCellNum()-1; can resolve this issue.
getLastCellNum() returns index plus one and once the counter will reach to end value, getCell(i) can point to the null value as per your code.
Actually i tried to export data in excel sheet and i have following code-
//Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet sheet = workbook.createSheet("User Data");
User user = new User();
ArrayList objcets = (ArrayList) user.fetchAll(request);
// first row for header
int rowNum = 1;
Row row = sheet.createRow(rowNum++);
int cellNum = 0;
// dynamic header sumbitted from form
if(request.getParameter("id")!=null && !request.getParameter("id").isEmpty())
{
cellNum++;
Cell cell = row.createCell(cellNum++);
cell.setCellValue("Id");
}
if(request.getParameter("fullName")!=null && !request.getParameter("fullName").isEmpty())
{
cellNum++;
Cell cell = row.createCell(cellNum++);
cell.setCellValue("Full Name");
}
if(request.getParameter("userName")!=null && !request.getParameter("userName").isEmpty())
{
cellNum++;
Cell cell = row.createCell(cellNum++);
cell.setCellValue("User Name");
}
if(request.getParameter("department")!=null && !request.getParameter("department").isEmpty())
{
cellNum++;
Cell cell = row.createCell(cellNum++);
cell.setCellValue("Department");
}
if(request.getParameter("email")!=null && !request.getParameter("email").isEmpty())
{
cellNum++;
Cell cell = row.createCell(cellNum++);
cell.setCellValue("Email");
}
UserEntity userObj;
for(int i=0; i<objcets.size();i++)
{
userObj = (UserEntity) objcets.get(i);
rowNum++;
row = sheet.createRow(rowNum++);
cellNum = 0;
if(request.getParameter("id")!=null && !request.getParameter("id").isEmpty())
{
cellNum++;
Cell cell = row.createCell(cellNum++);
cell.setCellValue(userObj.getId());
}
if(request.getParameter("fullName")!=null && !request.getParameter("fullName").isEmpty())
{
cellNum++;
Cell cell = row.createCell(cellNum++);
cell.setCellValue(userObj.getFullName());
}
if(request.getParameter("userName")!=null && !request.getParameter("userName").isEmpty())
{
cellNum++;
Cell cell = row.createCell(cellNum++);
cell.setCellValue(userObj.getUserName());
}
if(request.getParameter("department")!=null && !request.getParameter("department").isEmpty())
{
cellNum++;
Cell cell = row.createCell(cellNum++);
cell.setCellValue(userObj.getDepartment());
}
if(request.getParameter("email")!=null && !request.getParameter("email").isEmpty())
{
cellNum++;
Cell cell = row.createCell(cellNum++);
cell.setCellValue(userObj.getEmail());
}
But this generate error of class not found for XSSFWorkbook, to make it
workable I have to use Maven and inject dependency in pom.xml
I studied for Jxls to, and this also need POI and Meaven and I don't want to make use of Maven. My question is there anyway to export excel sheet without using Maven.
I could not find any blog regarding my question excel sheet without Maven.
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)
{
}
}
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);
}
}
private String[][] data;
// to read from excel file
public void readFile() throws IOException {
// Path to the excel file
// File datafile = new File("C:\\Users\\atomar\\Documents\test.xlsx");
// A Buffered File Input Stream to read the data
FileInputStream f = new FileInputStream(
"C:\\Users\\atomar\\Documents\\test.xlsx");
System.out.println("file found");
// InputStream fis = new BufferedInputStream(new FileInputStream("f"));
// We create a workbook which represents the excel file
XSSFWorkbook book = new XSSFWorkbook(f);
// Next a sheet which represents the sheet within that excel file
XSSFSheet sheet = book.getSheet("Sheet1");
// No of rows in the sheet
int rowNum = sheet.getLastRowNum() + 1;
System.out.println("rowNum");
// No of columns in the sheet
int colNum = sheet.getRow(0).getLastCellNum();
// A Two dimensional array of Strings which represents the data in the
// sheet
data = new String[rowNum][colNum];
{
for (int i = 0; i < rowNum; i++) {
// Get the row
XSSFRow row = sheet.getRow(i);
for (int j = 0; j < colNum; j++) {
// Get the columns or cells for the first row and keep
// looping
// for the other rows
XSSFCell cell = row.getCell(j);
// Make a call to the method cellToString which actually
// converts the cell contents to String
data[i][j] = cellToString(cell);
// data[i][j] = value;
// Here is where you write the logic to handle the data.I am
// just printing out the contents here.
//System.out.println("The value is " + data[i][j]);
}
}
Here I am calling that function
public void InterestedParty() throws InterruptedException {
try {
readFile();
} catch (IOException e1) {
}
}
Getting error: There are no support for this type of cell
I deleted two row data from input excel file then it started before it was working fine. But now I have deleted those row completely the also issue is there
if there is no data, XSSFCell will be null. Check whether it is null or not. After call your cellToString() method.
XSSFCell cell = row.getCell(j);
if(cell != null) {
data[i][j] = cellToString(cell);
} else {
// if you would like to set value when cell is null
row.createCell(j).setCellValue(your value);
}
You can have a row with data, an empty row next then another row with data. The middle row can be viewed as null if is undefined, so my advice is to use an iterator for the rows.
RowIteratior here is a good start.
Also, once you have the row, you can use cell iterator to iterate over the cells. Keep in mind that an undefined cell will be viewed as null and skipped, but an empty cell is not null!
Cell iterator is doc'ed here.
Your approach is also good, but you need to check for nulls or empty at each iteration before working with the objects.