I am trying to write my test results/data to excel at runtime for which I have written the below code. I am not getting any error while compiling this code however the results are not getting written in this. Can someone help me out with the problem?
public void WritetoExcel(String filepath, String OrderID) throws IOException
{
FileInputStream ExcelFile = new FileInputStream(filepath);
System.out.println(filepath);
ExcelWBook = new XSSFWorkbook(ExcelFile);
System.out.println("WorkBook Sucessfully");
ExcelWSheet = ExcelWBook.getSheetAt(0);
System.out.println("Sheet Sucessfully");
Iterator<Row> rowIterator= ExcelWSheet.iterator();
int RowNum =0;
while (rowIterator.hasNext())
{
Row row=rowIterator.next();
RowNum++;
}
try
{
Row = ExcelWSheet.createRow(RowNum);
Iterator<Cell> cellIterator=Row.iterator();
Cell = Row.getCell(0);
if (Cell==null)
{
Cell=Row.createCell(0);
Cell.setCellValue(OrderID);
}
else
{
Cell.setCellValue(OrderID);
}
FileOutputStream fileOut = new FileOutputStream(filepath);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
}
catch (Exception e )
{
throw (e);
}
}
I was going to make this a comment, but it is too long.
There are a few comments I can make about your code.
First, it seems you are iterating through and counting rows that exist in the sheet. Then you are creating a new row at that index. Since a spreadsheet could have missing rows, this will only work for a very specific type of spreadsheet. That is, one which has no missing rows, and you always want to add the next row in the next empty spot. Instead of:
Iterator<Row> rowIterator= ExcelWSheet.iterator();
int RowNum =0;
while (rowIterator.hasNext())
{
Row row=rowIterator.next();
RowNum++;
}
try
{
Row = ExcelWSheet.createRow(RowNum);
You can just as easily use:
int rowNum = ExcelWSheet.getLastRowNum() + 1;
Row row = ExcelWSheet.createRow(rowNum);
Then you write orderId in the first column of that row. Instead of:
Iterator<Cell> cellIterator=Row.iterator();
Cell = Row.getCell(0);
if (Cell==null)
{
Cell = Row.createCell(0);
Cell.setCellValue(OrderID);
}
else
{
Cell.setCellValue(OrderID);
}
You could just use:
Cell cell = row.createCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK);
cell.setCellValue(OrderID);
In addition, for this you don't even need the iterators, but when you really need to iterate through the rows and cells of a spreadsheet it is better to use the for each syntax like this:
for (Row row : sheet) {
for (Cell cell : row) {
// do something with the cell
}
}
Related
I am facing issue while writing the data to excel file.
I am using apache POI 4.1.2 version library.
Below is the sample code.
try {
outputStream = new FileOutputStream(EXCEL_FILE_PATH);
} catch (Exception e) {
System.out.println("Exception While writing excel file " + e.getMessage());
}
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("FileCompare");
Row row = sheet.createRow(0);
Cell cellfilename = row.createCell(0);
cellfilename.setCellValue("File Name");
Cell cellfilename1 = row.createCell(1);
cellfilename1.setCellValue("Difference in File 1");
Cell cellfilenam2 = row.createCell(2);
cellfilenam2.setCellValue("Difference in File 2");
for (int diffcol = 1; diffcol < 3; diffcol++) {
for (int i = 1; i < 57; i++) {
Row rows = sheet.createRow(i);
// System.out.println("Difference Coln number " + diffcol);
Cell diffcell = rows.createCell(diffcol);
diffcell.setCellValue("abacds");
/*
* Cell diffcell2 = row.createCell(2); diffcell2.setCellValue("abacds");
*/
}
}
try {
workbook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStream.flush();
outputStream.close();
workbook.close();
}
In this only last column cells is getting saved in excel file , previous cells are kept as blank.
Kindly help and let me know if I am doing something wrong?
Not sure about the actual api but I think you inner loop should create columns and your outer one should create rows like this
for (int row=1:row<57;row++)
{
Row rows = sheet.createRow(row);
for (int diffCol = 1; diffCol < 3; difCol++)
{
Cell diffcell = rows.createCell(diffcol);
diffcell.setCellValue("abacds");
}
}
The problem is that inside your loop you're always using sheet.createRow(i) to retrieve the row you need, but as the docs says (docs that are written not so clear, actually) this method is always recreating a brand new & empty row, deleting the existing one (if a row at that i-position was already present).
It means that each iteration of yuor loop is actually deleting previous rows creating brand new rows: at the end only rows created by the last iteration are surviving!
To solve you're problem, use sheet.createRow(i) only one time in order to create the row at i-position and then only use sheet.getRow(i) to retreive it.
So replace (in your code) the following wrong line
Row rows = sheet.createRow(i);
with the following code
Row row = sheet.getRow(i);
if (row == null) row = sheet.createRow(i);
where new row is created only if it does not already exist!
And you're done, it works like a charm!
I have a workbook which contains several sheets where are there some data. At the end of the position, there will be a sheet which will not have the data for the very first time.
In this case, I have to update the data like this.
Test Suite Name: xxxxx
TestCase ID Request1 Request2 Request3
1234567890 PASS FAIL PASS
For that I have written the code like this but its not performing as expected.
public void readAndUpdateBlankExcelCells()
{
String xlPath = "D:\\working\\POC\\RunManager.xls"
try
{
log.info ("Entered into Blank Method")
FileInputStream inputStream = new FileInputStream(new File(xlPath))
HSSFWorkbook myBook = new HSSFWorkbook(inputStream)
HSSFSheet sheet = myBook.getSheet("TestSuiteSummary")
HSSFRow row;
HSSFCell cell;
Iterator itr = sheet.rowIterator()
while(itr.hasNext())
{
row = (HSSFRow) itr.next()
System.out.println("Entered while loop")
for (int idx = 0; idx < row.getLastCellNum(); idx++)
{
System.out.println("Entered for loop")
cell = row.getCell(idx, Row.CREATE_NULL_AS_BLANK)
cell.setCellValue("Test Suite Name: Sample Test Suite")
}
System.out.println()
}
}
catch(Exception ex)
{
System.out.println("In catch")
ex.printStackTrace()
}
}
If its updated properly which I had mentioned in the above next TestSuite details should update in the next row...it will go for each test suite.
Can anyone tell me your suggestions?
Thanks
I have an app that imports an excel but the excel in question has black spaces in some of the cells, when I receive it puts those blank spaces in my database. I want to prevent that to happen, i tried to use regex and replace(" ","") and nothing work. Can you help me? This is my code:
File file = new File(inFileName);
Workbook workBook = WorkbookFactory.create(file);
Sheet sheet = workBook.getSheetAt(0);
int rowCtr = 34;
Row myRow = sheet.getRow(rowCtr++);
while (myRow != null) {
Cell nif = myRow.getCell(0);
Cell marcaexploracao = myRow.getCell(1);
Cell numerochip = myRow.getCell(2);
Cell marcaauricular = myRow.getCell(3);
Cell datanascimento = myRow.getCell(4);
//problem I mentioned is is in chipnumber only
bd.addAnimais(chipnumber.ToString().replaceFirst("/[^0-9]/","-"),marcaexploracao.toString(),marcaauricular.toString(),datanascimento.toString(),nif.toString(),0,"","","","",0);
myRow = sheet.getRow(rowCtr++);
}
}catch (Exception e){e.printStackTrace(); }
I am trying to create a pivot table to do cohort analysis
pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1);
pivotTable.addRowLabel(1);
this is giving me an error while opening the file that the file is corrupt do you want to still open the file, when I say yes and open it, the result looks fine, the only issue is the error.
I did a workaround to have a duplicate column data with different name
for ex:
say column 1 is email added a duplicate column 36 with name dup email and did as shown below, it works fine
pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1);
pivotTable.addRowLabel(35);
why in the first place it failed when I give both column and row label as 1.
Any help is greatly appreciated
If you set pivotTable.addRowLabel(1) using apache poi, then apache poi sets pivot field 1 only to be axisRow but it needs to be dataField too if you also want to pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1). So we neeed to correct this.
Example:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import java.io.*;
class PivotTableTest5 {
private static void setCellData(Sheet sheet) {
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Name");
cell = row.createCell(1);
cell.setCellValue("City");
for (int r = 1; r < 15; r++) {
row = sheet.createRow(r);
cell = row.createCell(0);
cell.setCellValue("Name " + ((r-1) % 4 + 1));
cell = row.createCell(1);
cell.setCellValue("City " + (int)((new java.util.Random().nextDouble() * 3)+1) );
}
}
public static void main(String[] args) {
try {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
//Create some data to build the pivot table on
setCellData(sheet);
XSSFPivotTable pivotTable = sheet.createPivotTable(
new AreaReference(new CellReference("A1"), new CellReference("B15")), new CellReference("H5"));
//Count the second column. This needs to be second column a data field.
pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 1);
//Use second column as row label
pivotTable.addRowLabel(1);
//Apache poi sets pivot field 1 (second column) only to be axisRow but it needs to be dataField too.
pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(1).setDataField(true);
FileOutputStream fileOut = new FileOutputStream("PivotTableTest5.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My scenario is to get text from "Status" column and based on text comparison ,I want to highlight that particular cell.Below is my code-
private static void colorSheet(String xlsxFileAddress)
{
try
{
FileInputStream file = new FileInputStream(new File(xlsxFileAddress));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFFormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
XSSFSheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type after eveluating formulae
//If it is formula cell, it will be evaluated otherwise no change will happen
switch (evaluator.evaluateInCell(cell).getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "tt");
break;
case Cell.CELL_TYPE_STRING:
{
System.out.print(cell.getStringCellValue() + "tt");
ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.EQUAL,"Extra Rows in new table");
org.apache.poi.ss.usermodel.PatternFormatting fill2 = rule2.createPatternFormatting();
fill2.setFillBackgroundColor(IndexedColors.BLUE.index);
fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
CellRangeAddress[] regions = {
CellRangeAddress.valueOf("A2:A7")
};
sheetCF.addConditionalFormatting(regions, rule2);
break;
}
}
}
System.out.println("");
}
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
I want that whichever cell has a text "Extra Rows in new table" should be highlighted in blue but my code is not working.please suggest needful.
Okay, the problem is that you're reading the file and changing its content in the process memory, but you never write the changes back into the file.
Try replacing:
file.close();
with:
file.close();
FileOutputStream writeFile = new FileOutputStream(new File(xlsxFileAddress));
workbook.write(writeFile);
writeFile.close();
It can be because of
ConditionalFormattingRule "Equal" will work only when it is given like ComparisonOperator.EQUAL, "\"" + "Extra Rows in new table" + "\"" instead of (ComparisonOperator.EQUAL,"Extra Rows in new table");
Add this after your file.close() in order to write back to the file.
FileOutputStream writeFile = new FileOutputStream(new
File(xlsxFileAddress));
workbook.write(writeFile);
writeFile.close();