Excel Found unreadable content -POI XSSFWorkbook setcellvalue - apache-poi

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.

Related

Unable to understand when "i "value is constant and 2 dimension array works fine on getting the value from each row correctly

Code :
public String[][] getExcelData(String excellocation, String sheetName) {
try {
String dataSets[][] = null;
FileInputStream file = new FileInputStream(new File(excellocation));
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheet(sheetName);
// count number of active rows
int totalRow = sheet.getLastRowNum();
// count number of active columns in row
int totalColumn = sheet.getRow(0).getLastCellNum();
// Create array of rows and column
dataSets = new String[totalRow][totalColumn];
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
DataFormatter formatter = new DataFormatter();
int i = 0;
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
int j = 0;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell.getStringCellValue().contains("TestCases")) {
break;
}
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
dataSets[i][j++] = cell.getStringCellValue();
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_STRING:
dataSets[i][j++] = cell.getStringCellValue();
System.out.println(cell.getStringCellValue());
break;
}
}
System.out.println("");
}
file.close();
return dataSets;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws IOException {
String excellocation = "C:\\Users\\Sivaranjani Gopal\\Desktop\\siva.xlsx";
String sheetName = "testdata";
ExcelReaderpg excel = new ExcelReaderpg();
Object[][] data = excel.getExcelData(excellocation, sheetName);
}
Note :
1.My Query is the value of i is always said to be 0. so dataset[0][1] for 1st row
for second row it should be dataset [1][0] [1][1] and so on.
why does i value remain the same and i get the desired output.
Can some one explain the value of i and j implementation in the array

Not able to run java code from Eclipse to Jmeter using Groovy

The code below prints the content from the excel file (tried in eclipse) but I am not able to run it in Jmeter 3.1 using Groovy.
I throws error:
Problem in JSR223 script JSR223 Sampler, message:
javax.script.ScriptException:
org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed
This is my code:
public static void main (String args[]) throws IOException
{
GetExcelTableInto2DArrayListString("C:\\Users\\val1\\Desktop\\Book1.xlsx", true);
}
public static void GetExcelTableInto2DArrayListString(String excelFile, boolean debug) throws IOException{
ArrayList<String> OUT = new ArrayList<String>();
File myFile = new File(excelFile);
FileInputStream fis = null;
fis = new FileInputStream(myFile);
String columnWanted = "PhysicalIDs";
Integer columnNo = null;
XSSFWorkbook myWorkBook = null;
myWorkBook = new XSSFWorkbook (fis);
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
// Get iterator to all the rows in current sheet
List<Cell> cells = new ArrayList<Cell>();
Row firstRow = mySheet.getRow(0); //rowIterator.next();
for(Cell cell:firstRow){
if (cell.getStringCellValue().equals(columnWanted)){
columnNo = cell.getColumnIndex();
}
}
System.out.println(columnNo);
DataFormatter formatter = new DataFormatter(Locale.US);
if (columnNo != null){
for (Row row : mySheet) {
Cell c = row.getCell(columnNo);
System.out.println(formatter.formatCellValue(c));
if (c == null) {
// Nothing in the cell in this row, skip it
} else {
cells.add(c);
}
}
}else{
System.out.println("could not find column " + columnWanted + " in first row of " + myFile.toString());
}
}
I strongly doubt that your code works in eclipse (whatever it is) and anywhere else because this line:
public static void main (String args[])
is not syntactically correct neither in Java nor in Groovy.
The "good" declaration of the entry point (although it's not required for Groovy scripts) would be:
public static void main(String[] args)
Full code just in case:
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.DataFormatter
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.xssf.usermodel.XSSFSheet
import org.apache.poi.xssf.usermodel.XSSFWorkbook
public static void main(String[] args) throws IOException {
GetExcelTableInto2DArrayListString("C:\\Users\\val1\\Desktop\\Book1.xlsx", true);
}
public static void GetExcelTableInto2DArrayListString(String excelFile, boolean debug) throws IOException {
ArrayList<String> OUT = new ArrayList<String>();
File myFile = new File(excelFile);
FileInputStream fis = null;
fis = new FileInputStream(myFile);
String columnWanted = "PhysicalIDs";
Integer columnNo = null;
XSSFWorkbook myWorkBook = null;
myWorkBook = new XSSFWorkbook(fis);
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
// Get iterator to all the rows in current sheet
List<Cell> cells = new ArrayList<Cell>();
Row firstRow = mySheet.getRow(0); //rowIterator.next();
for (Cell cell : firstRow) {
if (cell.getStringCellValue().equals(columnWanted)) {
columnNo = cell.getColumnIndex();
}
}
System.out.println(columnNo);
DataFormatter formatter = new DataFormatter(Locale.US);
if (columnNo != null) {
for (Row row : mySheet) {
Cell c = row.getCell(columnNo);
System.out.println(formatter.formatCellValue(c));
if (c == null) {
// Nothing in the cell in this row, skip it
} else {
cells.add(c);
}
}
} else {
System.out.println("could not find column " + columnWanted + " in first row of " + myFile.toString());
}
}
More information:
Lesson: A Closer Look at the "Hello World!" Application
Busy Developers' Guide to HSSF and XSSF Features
Apache Groovy - Why and How You Should Use It

Invalid header signature; read 0x6D78206C6D74683C, expected 0xE11AB1A1E011CFD0

Invalid header signature; read 0x6D78206C6D74683C, expected 0xE11AB1A1E011CFD0 getting the above error when I am trying to read excel sheet. xls format.
when I try to open the sheet manually I get this error : "The file format and extension of '*******.xls' don't match. The file could be corrupted or unsafe.
String strCompleteFilepath=this.strFilePath + File.separator +
this.strFileName;
int strRowIndex=0;
int strColIndex=0;
String strCompVal="";
try{
InputStream file = new FileInputStream(strCompleteFilepath);
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
int strRowCount= sheet.getLastRowNum();
if(strRowCount>0)
{
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = (Row)rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = (Cell)cellIterator.next();
String strCellValue=cell.toString();
if (strCellValue.contentEquals(strKeyIdentifier))
{
strRowIndex=cell.getRowIndex();
System.out.println("The row number where
"+strKeyIdentifier+"is found: "+strRowIndex);
}
if (strCellValue.contentEquals(strColName))
{
strColIndex=cell.getColumnIndex();
System.out.println("The column where "+strColName+" is
found: "+strColIndex);
}
}
}
HSSFCell CompValue=sheet.getRow(strRowIndex).getCell(strColIndex);
switch (CompValue.getCellType())
{
case 0:
if (DateUtil.isCellDateFormatted(CompValue))
{
strCompVal = CompValue.getDateCellValue().toString();
} else
{
strCompVal = String.valueOf(CompValue.getNumericCellValue());
}
break;
case 2:
strCompVal = String.valueOf(CompValue.getBooleanCellValue());
break;
case 1:
strCompVal = CompValue.getStringCellValue();
}
//strCompVal=CompValue.toString();
file.close();
FileOutputStream out = new FileOutputStream(new `
File(strCompleteFilepath));
workbook.write(out);
out.close();
}
else
{
System.out.println("There is no data in the excel, the row count is : "+strRowCount);
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
return strCompVal;

Selenium excel read and write to find row number

In my program I want to find the row number in the excel sheet matching the string I have passed as argument . It works fine for first and second row but problem is with the next rows. My code to find row number is as below :
public int findrownum(String sName, String value, int cNum) throws Exception{
File excel = new File(filepath);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet(sName);
boolean check = true;
int i=0;
while (check){
XSSFRow rowH = ws.getRow(i);
XSSFCell cell = rowH.getCell(cNum);
String cellvalue = cellToString(cell);
if (cellvalue.equals(value)){
check = false;
}
else {
i = i+1;
}
}
return i;
}
}
I want to read third row that is the string with name registration from the excel
Sl No test case name result timestamp
1 login Pass 03/03/2014 12:11:43 PM
2 Registration
Please let me know what changes needs to be done in the code .
Thanks
I used the similar logic as mentioned by #eric in JUNIT now i am able to find the row number .But now its giving error while i try to read the data using this row number . My code to read data is as below . Please let me know what changes needs to be done public String dataread(String sName, int rNum, String cName) throws Exception{
File excel = new File(filepath);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet(sName);
XSSFRow rowH = ws.getRow(rNum-1);
int totalRows = ws.getLastRowNum();
int i =0;
for(i=0;i<=totalRows;i++)
{
XSSFCell cell = rowH.getCell(i);
String value = cellToString(cell);
if (value.equals(cName)){
System.out.println(i);
break;
}
}
XSSFRow row = ws.getRow(rNum);
XSSFCell cell = row.getCell(i);
String value = cellToString(cell) return value;
}
In general From this Documentation you can use the getHeight() to get in which your cursor instead of writing up your own loop. Obviously this would reduce the execution time as well. Also the code which you have written could have caused the exception,as there is no more physical rows.
ws.getRow(i); can cause a fatal error if i>height of the last row
Hope the following code helps. The assumption is the data in the cell is string data. Also this is with apache poi api.
public static String getcellValue(int testRowNo, int colNo)
{
String projectPath = System.getProperty("user.dir");
String excelPath = projectPath + "/TestSet.xlsx";
File excel = new File(excelPath);
FileInputStream fis = null;
Workbook workBook = null;
String cellValue = null;
try
{
fis = new FileInputStream(excel);
workBook = WorkbookFactory.create(fis);
Sheet workSheet = workBook.getSheet(sheetName);
int totalRows = workSheet.getLastRowNum();
Row row = null;
cellValue = workSheet.getRow(testRowNo).getCell(colNo).getStringCellValue();
} catch (InvalidFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}finally
{
try
{
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return cellValue;
}
public static int getrowNumber(String sheetName, String cellData)
{
String projectPath = System.getProperty("user.dir");
String excelPath = projectPath + "/TestSet.xlsx";
File excel = new File(excelPath);
FileInputStream fis = null;
Workbook workBook = null;
String cellValue = null;
try
{
fis = new FileInputStream(excel);
workBook = WorkbookFactory.create(fis);
Sheet workSheet = workBook.getSheet(sheetName);
int totalRows = workSheet.getLastRowNum();
Row row = null;
int testRowNo = 0;
for(int rowNo =1; rowNo<=totalRows; rowNo++)
{
row = workSheet.getRow(rowNo);
testRowNo = testRowNo +1;
if(row.getCell(0).getStringCellValue().equalsIgnoreCase(cellData))
{
break;
}
}
} catch (InvalidFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}finally
{
try
{
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return testRowNo;
}

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;

Resources