Poi api XSSFWorkbook sheet cast EXCEPTION - java

package apsel5;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class A {
public static void main(String[] args) throws Exception{
FileInputStream f = new FileInputStream("D:\\LeadSuite.xlsx");
XSSFWorkbook wbks = new XSSFWorkbook(f);
Sheet s = (Sheet) wbks.getSheet("TestSteps");
Iterator itr = s.iterator();
while(itr.hasNext()){
Row rowitr = (Row)itr.next();
Iterator cellitr = rowitr.cellIterator();
while(cellitr.hasNext()){
Cell cell1= (Cell)cellitr.next();
switch(cell1.getCellType()){
case Cell.CELL_TYPE_STRING:
System.out.println(cell1.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell1.getNumericCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell1.getBooleanCellValue());
break;
}
}
}
}
}
I get an exception after running the above code:
Exception in thread "main" java.lang.ClassCastException:
org.apache.poi.xssf.usermodel.XSSFSheet cannot be cast to
org.apache.poi.sl.usermodel.Sheet

You imported the wrong version of Sheet. Simply turn
import org.apache.poi.sl.usermodel.Sheet;
into
import org.apache.poi.ss.usermodel.Sheet;
that represents the Excel worksheet, and your code should work. No cast should be needed for Sheet, Row and Cell.
If you look at the XSSFSheet class definition, you can see that it implements org.apache.poi.ss.usermodel.Sheet. On the other hand, the org.apache.poi.sl.usermodel.Sheet interface is related with PowerPoint; in fact, according to the Javadoc, it's the
Common parent interface for Slides, Notes and Masters
So .ss. = Excel (XSSF), and .sl. = PowerPoint (XSLF). The fact that these two interfaces have the same name may actually be misleading.

Related

can't find apache poi libraries

i'm trying for the first time the apache poi library to manage Execel files. I follow this steps to import apache poi: Import Apache POI in Intellij for JAVA.
The code compile without error but when i run it give me this error messages:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject
at Test.main(Test.java:16)
Caused by: java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
... 1 more
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\Huawei\\IdeaProjects\\untitled\\src\\TEST.xlsx");
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
Iterator<Row> itr = sheet.iterator();
while(itr.hasNext()){
Row row = itr.next();
Iterator<Cell> celliterator = row.cellIterator();
while(celliterator.hasNext()){
Cell cell = celliterator.next();
switch (cell.getCellType()){
case STRING: //field that represents string cell type
System.out.print(cell.getStringCellValue() + "\t\t\t");
break;
case NUMERIC: //field that represents number cell type
System.out.print(cell.getNumericCellValue() + "\t\t\t");
break;
default:
System.out.println("NOT NUMERIC AND NOT STRING");
}
}
}
}catch (Exception e ){
e.printStackTrace();
}
}
}
This seems like a classic Maven Project with a .jar downloaded not installed via mvn command.
If ClassNotFoundException raises in runtime, its because your project can't find the library after compiled.
Is this the case? If so, you must add the .jar via mvn install and declare him in your pom.xml. A better solution it's just adding the maven dependency directly:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>

Formatting Excel Spreadsheet using Apache POI in JAVA

My intention is to set the border for the contents of the spreadsheet data while maintaining the other properties of the cell as it is.
The below code formats(setting border) the whole spreadsheet rather than formatting only the portion of spreadsheet where there is actual data.
Is there a reason why the formatting is applied throughout the spreadsheet? And is there a way to overcome this?
package learning.selenium.self.begining;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class testing {
public static void main(String[] args) throws Exception {
File myFile = new File("TestFile.xlsx");
Workbook myWorkbook = WorkbookFactory.create(new FileInputStream(myFile));
Sheet mySheet = myWorkbook.getSheetAt(0);
Iterator<Row> r = mySheet.rowIterator();
while (r.hasNext()) {
Row myR = r.next();
Iterator<Cell> c = myR.cellIterator();
while (c.hasNext()) {
Cell myC = c.next();
System.out.println("precessing (" + myR.getRowNum() + "," + myC.getColumnIndex() + ")");
CellStyle s = myC.getCellStyle();
s = myC.getCellStyle();
s.setBorderBottom(BorderStyle.THIN);
s.setBorderTop(BorderStyle.THIN);
s.setBorderLeft(BorderStyle.THIN);
s.setBorderRight(BorderStyle.THIN);
myC.setCellStyle(s);
}
}
FileOutputStream fos = new FileOutputStream(myFile);
myWorkbook.write(fos);
fos.close();
}
}
I dont know if this helps but is worth checking out
CellRangeAddress range= new CellRangeAddress(firstrow, lastrow, firstcol, lastcol);
RegionUtil.setBorderBottom(BorderStyle.THIN, range, sheet);
Same way u can set for other borders.

Apache poi XLSX to XLS

I'm working with apache poi, i read some xlsx file, process it and then export them in xlsx format as well. But now i have the requirement of the export format to be XLS (this is to support old devices). Is there an easy way of convert the code-generated xlsx file to xls?
The all process is made with XSSF implementation.
Thanks in advance.
I agree with centic answer, but I want to add a few lines of code.
You said that you are using XSSF implementation.
So, for the workbook that you are saving do the following changes:
change XSSFWorkbook x = new XSSFWorkbook();
to Workbook x = new HSSFWorkbook();
where Workbook is import from org.apache.poi.ss.usermodel.Workbook;
Similarly
Change XSSFRow instantiation from
XSSFRow r = newXSSF();
to Row r = new HSSFRow();
and import the Row from org.apache.poi.ss.usermodel.Row;
Like the same way, change Cell instantiation to ss.usermodel package.
And finally save your HSSF workbook with .xls extension.
You will need to switch to the "ss" implementation which allows to transparently work with both HSSF (=XLS) and XSSF (=XSLX), see http://poi.apache.org/spreadsheet/converting.html for some details of the original HSSF -> SS switch which should also shed some light on supporting it for the other way around.
Then only the two constructors for HSSFWorkbook/XSSFWorkbook are needed to decide which of the two formats you want to produce.
I have faced same scenario and implemented below code for Coverting XLSX to XLS using Java
Below code will read it from directory and process using apache camel (polling file from path) and apace poi
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Optional;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
#Component
public class ExcelFileProcessor implements Processor {
final Logger logger = LoggerFactory.getLogger(getClass());
#Value("${test.dir.in}")
private String inDir;
#Override
public void process(Exchange exchange) throws Exception {
logger.info("Entry-ExcelFileProcessor- Process method");
long start = System.currentTimeMillis();
String fileNameWithExtn=(String) exchange.getIn().getHeader("camelFileName");
Long originalFileSize = (Long) exchange.getIn().getHeader("CamelFileLength");
String fileNameWithOutExtn = fileNameWithOutExtn(fileNameWithExtn);
logger.info("fileNameWithExtn:{}" ,fileNameWithExtn);
logger.info("fileNameWithOutExtn:{}" ,fileNameWithOutExtn);
logger.info("originalFileSize:{}" ,originalFileSize);
try(InputStream in = exchange.getIn().getBody(InputStream.class);
XSSFWorkbook wbIn = new XSSFWorkbook(in);
Workbook wbOut = new HSSFWorkbook();) {
int sheetCnt = wbIn.getNumberOfSheets();
for (int i = 0; i < sheetCnt; i++) {
Sheet sIn = wbIn.getSheetAt(0);
Sheet sOut = wbOut.createSheet(sIn.getSheetName());
Iterator<Row> rowIt = sIn.rowIterator();
while (rowIt.hasNext()) {
Row rowIn = rowIt.next();
Row rowOut = sOut.createRow(rowIn.getRowNum());
Iterator<Cell> cellIt = rowIn.cellIterator();
while (cellIt.hasNext()) {
Cell cellIn = cellIt.next();
Cell cellOut = rowOut.createCell(cellIn.getColumnIndex(), cellIn.getCellType());
switch (cellIn.getCellType()) {
case Cell.CELL_TYPE_BLANK: break;
case Cell.CELL_TYPE_BOOLEAN:
cellOut.setCellValue(cellIn.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
cellOut.setCellValue(cellIn.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
cellOut.setCellFormula(cellIn.getCellFormula());
break;
case Cell.CELL_TYPE_NUMERIC:
cellOut.setCellValue(cellIn.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
cellOut.setCellValue(cellIn.getStringCellValue());
break;
}
CellStyle styleIn = cellIn.getCellStyle();
CellStyle styleOut = cellOut.getCellStyle();
styleOut.setDataFormat(styleIn.getDataFormat());
cellOut.setCellComment(cellIn.getCellComment());
}
}
}
File outF = new File(inDir+fileNameWithOutExtn+".xls");
try(OutputStream out = new BufferedOutputStream(new FileOutputStream(outF));){
wbOut.write(out);
}
}catch (Exception e) {
logger.info("Error during Excel file process:{}",e.getMessage());
}
long end = System.currentTimeMillis();
logger.info("Total time processed for file in - {} ms", (end - start));
logger.info("Exit-FileProcessor- Process method");
}
public String fileNameWithOutExtn(String fileName) {
return Optional.of(fileName.lastIndexOf('.')).filter(i-> i >= 0)
.map(i-> fileName.substring(0, i)).orElse(fileName);
}
}
If you are not using camel and want to get inputstream from file use below snippet
String inpFn = "input.xlsx";
String outFn = "output.xls";
InputStream in = new BufferedInputStream(new FileInputStream(inpFn));
try {
Workbook wbIn = new XSSFWorkbook(in);
File outF = new File(outFn);
if (outF.exists())
outF.delete();
Workbook wbOut = new HSSFWorkbook();
//continue with above code

Error: Could not find or load main class excel2JSON.excel

package excel2JSON;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.json.JSONArray;
import org.json.JSONObject;
public class excel {
public static void main(String[] args)
{
String str = ExcelToJSON(new File ("C:\\workbook.xlsx"));
System.out.println("JSON = " + str);
}
private static String ExcelToJSON(File file_open)
{
JSONObject json = null;
try {
FileInputStream input = new FileInputStream(file_open);
Workbook workbook = WorkbookFactory.create(input);
Sheet sheet = workbook.getSheetAt(0);
json = new JSONObject();
JSONArray rows = new JSONArray();
for (Iterator<Row> rows_it = sheet.rowIterator(); rows_it.hasNext();) {
Row row = rows_it.next();
JSONObject jason_row = new JSONObject();
JSONArray cells = new JSONArray();
for (Iterator<Cell> cells_it = row.cellIterator(); cells_it.hasNext();) {
Cell cell = cells_it.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
double numeric=cell.getNumericCellValue();
cells.put(String.valueOf(numeric));
break;
case Cell.CELL_TYPE_STRING:
cells.put(cell.getStringCellValue());
break;
}
}
jason_row.put("cell", cells);
rows.put(jason_row);
}
// Create the JSON.
json.put("rows", rows);
} catch (Exception e) {
e.printStackTrace();
}
// Get the JSON text.
return json.toString();
}
}
getting this error:
Error: Could not find or load main class excel2JSON.excel
I don't know why i am getting this error. I am new to Java and i need help to fix this issue. I am trying to convert Excel file to JSON document. This is the code i wrote for that but i am getting issue when i run the program in Eclipse.
The most common cause of this error in eclipse is when you have moved the class around, Eclipse will be trying to use an outdated run configuration which will not work.
Click the down arrow next to the green play button in Eclipse, select Run Configurations.
Delete the references to this class, then close that window, select the excel class. Click the down arrow next to the play button again and select run as Java Application.

How do I use DataProvider with Apache POI

Please help!. Am newbie with Selenium frameworks, I have a method that accepts 5 parameters for booking a party. It uses TestNG DataProvider to read from excel file. The problem is(as shown below) It uses JXL imports which only supports XLS files (excel 2003 or older). I need help with a similar code that uses Apache POI instead so that it will support XLSX and new versions of excel (2007+). Can someone help me please?
package com.suite1;
import util.TestUtil;
import java.io.File;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class CreatePartyTest extends TestBase1 {
Workbook wb;
Sheet sh1;
int numrow;
#BeforeTest
public void beforeTest() throws IOException
{
initialize();
if (TestUtil.isSkip("CreatePartyTest"))
{
throw new SkipException("Skipping test, check run mode");
}
dr.get(CONFIG.getProperty("testSiteName"));
getobject("signin_link").click();
getobject("username_Signin_input").sendKeys("alexy.dsouza");
getobject("password_input").sendKeys("testing123");
getobject("submit_button").click();
}
#Test(dataProvider="Partydata")
public void createParty (String Partyname, String Date, String Firstname, String Lastname, String email, String mobile) throws InterruptedException
{
getobject("party_link").click();
getobject("start_party_link").click();
getobject("partyname_input").sendKeys(Partyname);
getobject("partydate_input").sendKeys(Date);
getobject("hostfirstname_input").sendKeys(Firstname);
getobject("hostlastname_input").sendKeys(Lastname);
getobject("hostemail_input").sendKeys(email);
getobject("hostmobile_input").sendKeys(mobile);
getobject("make_reservation").click();
}
//source
#DataProvider(name="Partydata")
public Object[][] TestDataFeed(){
try {
// load workbook: this is where i store my excel
wb=Workbook.getWorkbook(new File("C://Workspace//Max//excelfiles//Partydata.xls"));
// load sheet in my case I am referring to first sheet only
sh1= wb.getSheet(0);
// get number of rows so that we can run loop based on this
numrow= sh1.getRows();
}
catch (Exception e)
{
e.printStackTrace();
}
// Create 2 D array and pass row and columns
Object [][] Accountdata=new Object[numrow-1][sh1.getColumns()];
// This will run a loop and each iteration it will fetch new row
for(int i=0,j=1;i<numrow-1;i++){
// Fetch first row Accountname
Accountdata[i][0]=sh1.getCell(0,j).getContents();
// Fetch first row BankName
Accountdata[i][1]=sh1.getCell(1,j).getContents();
// Fetch everything else before an empty column
Accountdata[i][2]=sh1.getCell(2,j).getContents();
Accountdata[i][3]=sh1.getCell(3,j).getContents();
Accountdata[i][4]=sh1.getCell(4,j++).getContents();
}// Return 2d array object so that test script can use the same
return Accountdata;
}
}
I cannot solve your exact query , but you can take reference from my code in which i have used .xlsx workbook only and it is working fine for me.
I am able to read data from excel sheet(.xlsx) .
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class DataProvidersConcept {
#DataProvider(name="Excelsheet")
public Object[][] readData() throws Exception
{
File f = new File("C:/Users/Vikrant/Documents/MavenTesting.xlsx");
FileInputStream fis = new FileInputStream(f);
XSSFWorkbook workBook = (XSSFWorkbook) WorkbookFactory.create(fis);
XSSFSheet sheet=workBook.getSheet("Sheet1");
Object array[][]=new Object[2][2];
for(int i =0;i<2;i++)
{
for( int j=0;j<2;j++)
{
array[i][j]=sheet.getRow(i).getCell(j).toString();
}
}
return array;
}
#Test(dataProvider="Excelsheet")
public void testData(String Username , String password)
{
System.out.println(Username);
System.out.println("Username tested successfully");
System.out.println(password);
System.out.println("password tested successfully");
}
}
enter code here

Categories