Apache POI: Cannot change cell value - java

I have a program that takes a workbook, writes some data into it and then sets all cells on the first row to wow, using this method:
public void test(String sheetName, int columnSize) {
Row headerRow = workbook.getSheet(sheetName).getRow(0);
for (int i=0; i<columnSize; i++) {
cell.setCellValue("wow");
}
}
It is called from inside this method:
public void write(List<List<String>> rows, List<String> columns,
String sheetName, int startRow)
throws IOException {
Sheet sheet = workbook.getSheet(sheetName);
if (sheet==null) {
sheet = workbook.createSheet(sheetName);
}
if (startRow==0) {
clearWorkbook();
Row headerRow = sheet.createRow(0);
int k=0;
for(int c=0; c<columns.size(); c++) {
String column = columns.get(c);
Cell cell = headerRow.createCell(c);
cell.setCellValue(column);
}
}
int currentRow = Math.max(1, startRow);
for (int i = 0; i <rows.size(); i++) {
List<String> rowData = rows.get(i);
Row row = sheet.createRow(currentRow++);
row.setHeight((short) 2400);
for (int j=0; j<columns.size(); j++) {
Cell cell = row.createCell(j);
cell.setCellValue(rowData.get(j));
}
}
System.out.println("finished editing");
// Resize all columns to fit the content size
for(int z = 0; z < columns.size(); z++) {
sheet.autoSizeColumn(z);
sheet.setColumnWidth(z, Math.min(20000, sheet.getColumnWidth(z)));
}
System.out.println("finished resizing");
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream(workbookName);
workbook.write(fileOut);
fileOut.close();
System.out.println("closing");
test(sheetName, columns.size()); //<<--------------------------
System.out.println("closed: " + workbookFile.getAbsolutePath());
}
However it doesn't effect cells at all. What am I doing wrong?

You need to call test() before writing the workbook to FileOutputStream.

Related

how to read data from excel, having only one column

//method contains:
public Object[][] getExcelData(String excelLocation) {
Object[][] dataSet = null;
try {
file = new FileInputStream(excelLocation);
wrkbook = new XSSFWorkbook(file);
wrkbook.close();
sheet = wrkbook.getSheetAt(0);
// to get total active row count
int rowNum = sheet.getLastRowNum();
// to get total active column count
int colNum = sheet.getRow(0).getLastCellNum();
dataSet = new Object[rowNum][colNum];
for (int i = 0; i <rowNum; i++) {
XSSFRow row = sheet.getRow(i);
for (int j = 0; j <=colNum; j++) {
XSSFCell cell = row.getCell(j);
String value = String.valueOf(cell);
dataSet[i][j] = value;
}
}
return dataSet;
} catch (Exception e) {
e.printStackTrace();
}
return null;
// return null if for any exception
If you want to return the column values from the spreadsheet as a 2d array, change the signature of your method to return an array of type String[][], iterate over each row of the spreadsheet, adding the value of all of its columns to the array, and return the Array when you're done. I haven't tested this but it should be pretty close:
public static String[][] getDataSetAsArray(XSSFSheet pSheet) {
int iRowCount = pSheet.getLastRowNum();
int iColumnCount = pSheet.getRow(pSheet.getFirstRowNum()).getLastCellNum();
String[][] strDataVals = new String[iRowCount][iColumnCount];
for (int r = 0; r <= iRowCount; r++) {
XSSFRow row = pSheet.getRow(r);
for (int c = 0; c <= iColumnCount; c++) {
strDataVals[r][c] = row.getCell(c).getStringCellValue();
}
}
return strDataVals;
}

Not able to check in excel using Apache POI if specific cell as per row and column is empty in Selenium with Java

I'm trying to write data in excel while running my tests and in Excel Test Class I have written a code to check if specific row under column is empty then write data else increment the row by 1 and then check same and write data.
From another class I'm calling ExcelTest:
ExcelTest sfName = new ExcelTest("C:\\Users\\abc\\eclipse-workspace\\dgc\\src\\com\\dg\\base\\utility\\TestData.xlsx");
sfName.setCellData("Sheet1","SingleFactor Campaign",SFCampName);
ExcelTest Class
public class ExcelTest
{
public FileInputStream fis = null;
public FileOutputStream fos = null;
public XSSFWorkbook workbook = null;
public XSSFSheet sheet = null;
public XSSFRow row = null;
public XSSFCell cell = null;
String xlFilePath;
boolean isEmptyStringCell;
public ExcelTest(String xlFilePath) throws Exception
{
this.xlFilePath = xlFilePath;
fis = new FileInputStream(xlFilePath);
workbook = new XSSFWorkbook(fis);
fis.close();
}
public void setCellData(String sheetName, String colName, int rowNum, String value)
{
try
{
int col_Num = -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++)
{
if(row.getCell(i).getStringCellValue().trim().equals(colName))
{
col_Num = i;
}
}
sheet.autoSizeColumn(col_Num);
for(int j=2; j<7; j++)
{
row = sheet.getRow(j - 1);
if(row==null)
row = sheet.createRow(j - 1);
cell = row.getCell(col_Num);
isEmptyStringCell=cell.getStringCellValue().trim().isEmpty();
if (this.isEmptyStringCell)
{
cell = row.createCell(col_Num);
cell.setCellValue(value);
break;
}
else
{
j=j+1;
}
}
/*row = sheet.getRow(rowNum - 1);
if(row==null)
row = sheet.createRow(rowNum - 1);
cell = row.getCell(col_Num);
if(cell == null)
cell = row.createCell(col_Num);
cell.setCellValue(value);*/
System.out.println("The cell value is "+cell.getStringCellValue());
fos = new FileOutputStream(xlFilePath);
workbook.write(fos);
fos.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
If we remove the block comment(mentioned above in code and add then comment to this code listed below then it will just write data in cell whichever is provided while calling the function.
In below code I'm starting a loop till max 7 rows and then checking if the cell contains data then increment or write data and once it writes then exit the loop.
for(int j=2; j<7; j++)
{
row = sheet.getRow(j - 1);
if(row==null)
row = sheet.createRow(j - 1);
cell = row.getCell(col_Num);
isEmptyStringCell=cell.getStringCellValue().trim().isEmpty();
if (this.isEmptyStringCell)
{
cell = row.createCell(col_Num);
cell.setCellValue(value);
break;
}
else
{
j=j+1;
}
}
Expected: It should write data in a row which has no cell data.
Actual: It doesn't write anything.
I've found solution for the above question and only need to change few code and now it is working as expected:
for(int j=2; j<7; j++)
{
row = sheet.getRow(j - 1);
if(row==null)
row = sheet.createRow(j - 1);
cell = row.getCell(col_Num);
//it will check if cell contains no value then create cell and set value
if(cell == null)
{
cell = row.createCell(col_Num);
cell.setCellValue(value);
break;
}
}

read multiple excel sheet selenium-webdriver, java, eclipse

I want to run selenium-webdriver-java-eclipse, using excel file contains multiple excel sheets with different name(sheet1,sheet2,sheet3,...), i need a for loop help me to do that and read from this sheets.
public class ExcelDataConfig {
XSSFWorkbook wb;
XSSFSheet sheet = null;
public ExcelDataConfig(String Excelpath) throws IOException {
// TODO Auto-generated method stub
try {
File file = new File(Excelpath);
// Create an object of FileInputStream class to read excel file
FileInputStream fis = new FileInputStream(file);
wb = new XSSFWorkbook(fis);
} catch (Exception e) {
}
}
public String GetData(int sheetNumber, int Row, int Column) {
Iterator<Row> rowIt=sheet.rowIterator();
DataFormatter formatter = new DataFormatter();
XSSFCell cell = sheet.getRow(Row).getCell(Column);
String data = formatter.formatCellValue(cell);
return data;
}
public int GetRowCount(String sheetNumber) {
int row = wb.getSheet(sheetNumber).getLastRowNum();
row = row + 1;
return row;
}
}
try something like this, it is working for me you need to add the sheet numbers and cell numbers at the places of k and j
enter code here
String filePath="C:\\Users\\USER\\Desktop\\Book1.xlsx";// file path
FileInputStream fis=new FileInputStream(filePath);
Workbook wb=WorkbookFactory.create(fis);
ArrayList<String> ls=new ArrayList<String>();
for(int k=0; k<=3;k++)//k =sheet no
{
Sheet sh=wb.getSheetAt(k);
System.out.println(sh);
// int count=0;
for(int i=0;i<=sh.getLastRowNum();i++)
{
System.out.println("row no:"+i);
for(int j=0; j<=4;j++)//j=column no
{
try {
String values=sh.getRow(i).getCell(j).getStringCellValue().trim();
System.out.println(values);
//condetions
/* if(values.contains("condtn1"))
{
System.out.println("Value of cell "+values+" ith row "+(i+1));
ls.add(values);
count++;
}
if(values.contains("condn2"))
{
System.out.println("Value of cell "+values+" ith row "+(i+1));
ls.add(values);
count++;
}*/
}catch(Exception e){
}
}
}
}
}
}
Please try writing similar to something like this:
for (int i = startRow; i < endRow + 1; i++) {
for (int j = startCol; j < endCol + 1; j++) {
testData[i - startRow][j - startCol] = ExcelWSheet.getRow(i).getCell(j).getStringCellValue();
Cell cell = ExcelWSheet.getRow(i).getCell(j);
testData[i - startRow][j - startCol] = formatter.formatCellValue(cell);
}
}
Terms used in method are pretty self explanatory. Let us know if you get stuck or need more info.

Reading from excel file with blank cells to 2d array

I have a following code that reads logins and passwords from xls file starting from the second row(it skips column names) and writes it into a 2d array. But it only works if the sheet doesn't have blank cells in any of the rows. What should i do to make it work with empty cells?
private static Object[][] getUsersFromXls(String sheetName) {
final File excelFile = new File("src//resources//TestData.xls");
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(excelFile);
workbook = new HSSFWorkbook(fileInputStream);
} catch (IOException e) {
e.printStackTrace();
}
sheet = workbook.getSheet(sheetName);
final int numberOfRows = sheet.getLastRowNum();
final int numberOfColumns = sheet.getRow(0).getLastCellNum();
final String[][] xlsData = new String[numberOfRows][numberOfColumns];
String cellValue;
for (int i = 1; i <= numberOfRows; i++) {
final HSSFRow row = sheet.getRow(i);
for (int j = 0; j < numberOfColumns; j++) {
final HSSFCell cell = row.getCell(j);
final int cellType = cell.getCellType();
if (cellType == HSSFCell.CELL_TYPE_FORMULA) {
throw new RuntimeException("Cannot process a formula. Please change field to result of formula.");
} else {
cellValue = String.valueOf(cell);
xlsData[i - 1][j] = cellValue;
}
}
}
return xlsData;
}

Creating multiple sheets using Apache poi and servlets

When i am creating multiple sheets using Apache poi and servlets. It is creating the sheet but not writing the data to file. I am trying to write the first 1000 records to sheet1 and next 1000 to sheet2 through below code, but not working
private void writeDataToExcelFile(String string,
ArrayList<ArrayList<String>> excelData, OutputStream outputStream) {
HSSFWorkbook myWorkBook = new HSSFWorkbook();
String sheetName = "";
sheetName = "Document-" + 0;
HSSFSheet mySheet = myWorkBook.createSheet();
HSSFRow myRow = null;
HSSFCell myCell = null;
for (int rowNum = 0; rowNum < excelData.size(); rowNum++) {
ArrayList<String> rowData = excelData.get(rowNum);
if(rowNum>0 && rowNum%1000 == 0)
{
sheetName = "Document-" + (rowNum/1000);
mySheet = myWorkBook.createSheet();
}
myRow = mySheet.createRow(rowNum);
for (int cellNum = 0; cellNum < rowData.size(); cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(rowData.get(cellNum));
}
}
System.out.println("Last row:" + mySheet.getLastRowNum());
System.out.println("Row number:" + mySheet.rowIterator().next().getRowNum());
try {
myWorkBook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
What is wrong with my logic.Please do the needful help.
Thanks
When you loop through the dataset, you are wanting to split at row 1000 to start a new sheet, which is fine, however when you start the new sheet, the next row you create is row 1001 (the outer loop index variable)
myRow = mySheet.createRow(rowNum);
To get the effect you wish, change the loop to be something like this:
int currentRow = 0;
for (int rowNum = 0; rowNum < excelData.size(); rowNum++)
{
ArrayList<String> rowData = excelData.get(rowNum);
if(currentRow == 1000)
{
sheetName = "Document-" + (rowNum/1000);
mySheet = myWorkBook.createSheet();
currentRow = 0;
}
myRow = mySheet.createRow(currentRow);
for (int cellNum = 0; cellNum < rowData.size(); cellNum++)
{
myCell = myRow.createCell(cellNum);
myCell.setCellValue(rowData.get(cellNum));
}
currentRow++;
}
I haven't compiled this, so I don't know if it'll work right away, but it should point you in the right direction.
HTH
Edit
Thinking about this further, you could get the same effect from making a 1 line change to the original application (albeit losing a little bit of clarity):
myRow = mySheet.createRow(rowNum%1000);

Categories

Resources