Program terminates when reading data from excel in selenium web driver - excel

I am matching console output value with excel data. And in excel try to putting "TRUE" or "FALSE" if match found. My program is given below :
WebDriver driver = new FirefoxDriver();
driver.get("http://en.wikipedia.org/wiki/Software_testing");
String title = driver.getTitle();
System.out.println(title);
FileInputStream input = new FileInputStream("D:\\book.xls");
FileOutputStream webdata = new FileOutputStream ("D:\\book.xls");
int count=0;
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sh = wb.getSheet("sheet1");
HSSFRow row = sh.getRow(count);
String data = row.getCell(1).toString();
System.out.println(data);
if(title==data)
{
row.createCell(10).setCellValue("TRUE");
wb.write(webdata);
}
else
{
row.createCell(10).setCellValue("FALSE");
wb.write(webdata);
}
wb.close();
input.close();
driver.close();
When program reach here : HSSFWorkbook wb = new HSSFWorkbook(input); It terminates. I have debug it but not getting solution. can anyone help please?
I am getting below error in console :
Exception in thread "main" java.io.IOException: Unable to read entire header; 0 bytes read; expected 512 bytes
at org.apache.poi.poifs.storage.HeaderBlock.alertShortRead(HeaderBlock.java:227)
at org.apache.poi.poifs.storage.HeaderBlock.readFirst512(HeaderBlock.java:208)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:104)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:128)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:361)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:342)
at mhover.main(mhover.java:52)

Issue it solved now. Problem was like :
FileInputStream input = new FileInputStream("D:\\book.xls");
FileOutputStream webdata = new FileOutputStream ("D:\\book.xls");
Above code was overwriting my excel file data and was making excel blank. So I moved code : FileOutputStream webdata = new FileOutputStream ("D:\book.xls"); once data reading process complete. so its working now.
New & Working code :
//CODE TO REMOVE UNNECESSARY WARNING
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
//CALL FIREFOX DRIVER TO OPEN IT
WebDriver driver = new FirefoxDriver();
driver.get("http://en.wikipedia.org/wiki/Software_testing");
String title = driver.getTitle();
System.out.println(title);
FileInputStream input = new FileInputStream("D:\\sel.xls");
int count=0;
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sh = wb.getSheet("sheet1");
HSSFRow row = sh.getRow(count);
String data = row.getCell(1).toString();
System.out.println(data);
FileOutputStream webdata = new FileOutputStream ("D:\\sel.xls");
if(title.equals(data))
{
row.createCell(10).setCellValue("TRUE");
wb.write(webdata);
}
else
{
row.createCell(11).setCellValue("FALSE");
wb.write(webdata);
}
driver.close();
wb.close();
input.close();
}
}

Related

The file format and extension of <filename>.xls don't match -- apache-poi 4.1.2

I am creating xls with apache-poi version 4.1.2. when I do with junit it is working correctly but if I use tomee with container then the generated file is showing an error like
The file format and extension of <filename>.xls don't match
Java version 1.8
tomee-plus 1.7.5
K8s docker container
Using HSSFWorkbook
File outputFile = new File(dir, fileParameter.getFileName());
if (outputFile.exists() && !FileUtils.deleteFile(outputFile)) {
LOG.warn("Cannot delete");
}
try (final HSSFWorkbook workbook = new HSSFWorkbook()) {
final HSSFSheet sheet = workbook.createSheet(SUMMARY_SHEET_NAME);
//Header Row
int rowNum = 0;
int cellNum = 0;
HSSFRow row = sheet.createRow(rowNum++);
row.createCell(cellNum++).setCellValue("TEST1");
row.createCell(cellNum++).setCellValue("TEST2");
row.createCell(cellNum++).setCellValue("TEST3");
row.createCell(cellNum++).setCellValue("TEST4");
row.createCell(cellNum++).setCellValue("TEST5");
try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
workbook.write(fileOutputStream);
}
}

How to reduce memory while we Zip a big excel file in java

I am trying to zip a 30Mb excel file.
Wrapping th fileinputstream and fileoutputstream reduced some of the memory consumption.
Please suggest if you have a better option than this approach.
Do you think, flushing the ZipOutputStream after zos.write() inside while loop will be of any advantage?
Following is the code which i use.
public void zipBigFile()
throws IOException, ParseException {
String outFileName= "D:/Out/Big.zip";
File file = new File(outFileName);
FileOutputStream out = new FileOutputStream(file);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(out));
byte[] buffer = new byte[1024 * 8];
String inFileName = "D:/In/Big_File.xlsx";
FileInputStream fis = new FileInputStream(inFileName);
BufferedInputStream bis = new BufferedInputStream(fis);
ZipEntry zipEntry = new ZipEntry("Big_File_Zipped.xlsx");
zos.putNextEntry(zipEntry);
int length;
while ((length = bis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
fis = null;
buffer = null;
zos.flush();
zos.close();
out.close();
out = null;
zos = null;
}

XLSX removing sheets OutOfMemory Exception

I am trying to load the XLSX file using POI library that has 5 sheets. Size of the file is 5 MB. Total records in all sheets are around 30,000.
Once the file is loaded i need to delete the 1 or more sheets on the fly based on sheet neame as input.
Here is the snippet.
public void generateReportWorkBook(String[] requestedReports) throws Exception {
// Read the file
String dailyTicketReport = ReportConstants.REPORT_PATH + ReportConstants.FILE_NAME + ReportConstants.XLSX_FILE_EXTN;
FileInputStream fis = null;
XSSFWorkbook book = null;
try {
fis = new FileInputStream(dailyTicketReport);
book = new XSSFWorkbook(fis);
for (int i = book.getNumberOfSheets() - 1; i >= 0; i--) {
XSSFSheet tmpSheet = book.getSheetAt(i);
if (!ArrayUtils.contains(requestedReports, tmpSheet.getSheetName())) {
book.removeSheetAt(i);
}
}
} catch (Exception e) {
logger.error("Error occured while removing the sheets from workbook");
throw e;
} finally {
IOUtils.closeQuietly(fis);
}
}
When i execute the program. I get OutofMemory Exception.
How can i remove the sheets without memory issue.
I too faced the same issue of OOM while parsing xlsx file...after two days of struggle, I finally found out the below code that was really perfect;
This code is based on sjxlsx. It reads the xlsx and stores in a HSSF sheet.
// read the xlsx file
SimpleXLSXWorkbook = new SimpleXLSXWorkbook(new File("C:/test.xlsx"));
HSSFWorkbook hsfWorkbook = new HSSFWorkbook();
org.apache.poi.ss.usermodel.Sheet hsfSheet = hsfWorkbook.createSheet();
Sheet sheetToRead = workbook.getSheet(0, false);
SheetRowReader reader = sheetToRead.newReader();
Cell[] row;
int rowPos = 0;
while ((row = reader.readRow()) != null) {
org.apache.poi.ss.usermodel.Row hfsRow = hsfSheet.createRow(rowPos);
int cellPos = 0;
for (Cell cell : row) {
if(cell != null){
org.apache.poi.ss.usermodel.Cell hfsCell = hfsRow.createCell(cellPos);
hfsCell.setCellType(org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING);
hfsCell.setCellValue(cell.getValue());
}
cellPos++;
}
rowPos++;
}
return hsfSheet;

Apache POI - How to write to XLS in parts

I use Apache POI and I have a lot of data that I want to write to *.xls file in parts.
Now I use:
FileOutputStream fileOutputStream = null;
File tmpFile = new File("blabla.xls");
Workbook workbook = null;
try {
for(int i = 1; i <= pageNumber; i++) {
workbook = xlsGenerator.generateWorkbook(someData, i);
fileOutputStream = new FileOutputStream(tmpFile);
workbook.write(fileOutputStream);
}
}
But it doesn't work. It always replace old data instead of appending new data to workbook. So, are there ways to write in parts?

Excel Found unreadable content -POI XSSFWorkbook setcellvalue

I am trying to setcellvalue for xlsx file , Program works fine with no error , but while opening the xlsx file it throws an error saying Excel Found unreadable content
public boolean setCellData(String sheetName,String colName,int rowNum, String data){
try{
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(path);
if(rowNum<=0)
return false;
int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1)
return false;
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 false;
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 false;
}
return true;
}
You have initialized FileInputStream, but not used that. Please replace
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(path);
with
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
this works on my end and not showing any error.

Resources