ACE IBM Reading XLSX Excel with java compute node - java

im new in ACE. I want to create a flow that reads xlsx excel file using java and prints it to the database. Which nodes should I use for this task and is it correct to use only this java compute code as java code?
/*
JAR files to be added to shared-classes folder under server or integration node dir:
dom4j-1.6.1.jar
names.txt
poi-3.9-20121203.jar
poi-ooxml-3.9-20121203.jar
poi-ooxml-schemas-3.9-20121203.jar
xmlbeans-2.3.0.jar
*/
import com.ibm.broker.javacompute.MbJavaComputeNode;
import com.ibm.broker.plugin.MbElement;
import com.ibm.broker.plugin.MbException;
import com.ibm.broker.plugin.MbMessage;
import com.ibm.broker.plugin.MbMessageAssembly;
import com.ibm.broker.plugin.MbOutputTerminal;
import com.ibm.broker.plugin.MbUserException;
import com.ibm.broker.plugin.MbXMLNSC;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
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 class ParseExcel extends MbJavaComputeNode {
public void evaluate(MbMessageAssembly inAssembly) throws MbException {
MbOutputTerminal out = getOutputTerminal("out");
// MbOutputTerminal alt = getOutputTerminal("alternate");
MbMessage inMessage = inAssembly.getMessage();
MbMessageAssembly outAssembly = null;
try {
// create new message as a copy of the input
MbMessage outMessage = new MbMessage(inMessage);
outAssembly = new MbMessageAssembly(inAssembly, outMessage);
// ----------------------------------------------------------
// Add user code below
// get InputBody
MbElement inputBlob = inAssembly.getMessage().getRootElement().getLastChild();
byte[] originalMsgByteArray = (byte[])inputBlob.getLastChild().getValue();
InputStream stream = new ByteArrayInputStream(originalMsgByteArray);
parseXLSX(stream, outMessage);
// End of user code
// ----------------------------------------------------------
} catch (MbException e) {
// Re-throw to allow Broker handling of MbException
throw e;
} catch (RuntimeException e) {
// Re-throw to allow Broker handling of RuntimeException
throw e;
} catch (Exception e) {
// Consider replacing Exception with type(s) thrown by user code
// Example handling ensures all exceptions are re-thrown to be handled in the flow
throw new MbUserException(this, "evaluate()", "", "", e.toString(),
null);
}
// The following should only be changed
// if not propagating message to the 'out' terminal
out.propagate(outAssembly);
}
public void parseXLSX(InputStream fis, MbMessage outMessage){
try {
MbElement outRoot = outMessage.getRootElement();
// create XMNLSC parser
MbElement outBody = outRoot.createElementAsLastChild(MbXMLNSC.PARSER_NAME);
// Create root element.
MbElement excelRoot = outBody.createElementAsLastChild(MbElement.TYPE_NAME, "excel", null);
DataFormatter formatter = new DataFormatter();
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 = wb.getSheetAt(0);
for (Row row : sheet1) {
// create a row element for current excel row.
MbElement rowMsgElement = excelRoot.createElementAsLastChild(MbElement.TYPE_NAME, "row", null);
for (Cell cell : row) {
// get cell value as text
String text = formatter.formatCellValue(cell);
// create an element called cell in output message with value as cell value
rowMsgElement.createElementAsLastChild(MbElement.TYPE_NAME,"cell",text);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I tried to add 2 java project in independent resources which reads the excel correctly but i dont know how to add them into flow.First code introduces the table and writes excel to console:
public class GFKTable {
private String reportingProductGroup;
private String region;
private String year;
private String month;
private String brand;
private int salesUnits;
private float salesUnitPercentage;
public GFKTable(){}
public GFKTable(String reportingProductGroup, String region, String year, String month,
String brand,int salesUnits,float salesUnitPercentage) {
super();
this.reportingProductGroup = reportingProductGroup;
this.region = region;
this.year = year;
this.month = month;
this.brand = brand;
this.salesUnits = salesUnits;
this.salesUnitPercentage =salesUnitPercentage;
}
#Override
public String toString() {
return "GFK Table[reportingProductGroup=" + reportingProductGroup + ", region=" +region+", year=" + year + ", month=" + month
+ ", brand=" + brand + ", salesUnits="+salesUnits+", salesUnitPercentage="+salesUnitPercentage+"]";
}
public String getReportingProductGroup() {
return reportingProductGroup;
}
public void setReportingProductGroup(String reportingProductGroup) {
this.reportingProductGroup = reportingProductGroup;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region= region;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getBrand(String brand) {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getSalesUnits(int salesUnits) {
return salesUnits;
}
public void setSalesUnits(int salesUnits) {
this.salesUnits = salesUnits;
}
public float getSalesUnitPercentage(float salesUnitPercentage) {
return salesUnitPercentage;
}
public void setSalesUnitPercentage(float salesUnitPercentage) {
this.salesUnitPercentage = salesUnitPercentage;
}
}
second code reads the xlsx excel
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadXLSX {
public static void main(String[] args) {
List<GFKTable> gfkList = readXLSXFile("C:\\Users\\Y9GAMF862\\Desktop\\GFKbosluksuz.xlsx");
for(GFKTable gfk : gfkList){
System.out.println(gfk);
}
}
private static List<GFKTable> readXLSXFile(String file) {
List<GFKTable> listGfk = new ArrayList<GFKTable>();
try {
XSSFWorkbook work = new XSSFWorkbook(new FileInputStream(file));
XSSFSheet sheet = work.getSheet("Sheet1");
XSSFRow row;
int i=1;
int salesUnit;
String reportingProductGroup,region,month,brand,year;
float salesUnitPercentage;
while((row = sheet.getRow(i))!=null){
try{
reportingProductGroup = row.getCell(0).getStringCellValue();
}
catch(Exception e){reportingProductGroup = null;}
try{
region = row.getCell(1).getStringCellValue();
}
catch(Exception e){region = null;}
try{
year = row.getCell(2).getStringCellValue();
}
catch(Exception e){year = null;}
try{
month = row.getCell(3).getStringCellValue();
}
catch(Exception e){month = null;}
try{
brand = row.getCell(4).getStringCellValue();
}
catch(Exception e){brand= null;}
try{
salesUnit = (int) row.getCell(5).getNumericCellValue();
}
catch(Exception e){salesUnit = 0;}
try{
salesUnitPercentage = (float) row.getCell(6).getNumericCellValue();
}
catch(Exception e){salesUnitPercentage = 0;}
GFKTable gfk = new GFKTable(reportingProductGroup,region,year,month,brand,salesUnit,salesUnitPercentage);
listGfk.add(gfk);
i++;
}
work.close();
} catch (IOException e) {
System.out.println("Exception is GFKTable fetch data :: "+e.getMessage());
e.printStackTrace();
}
return listGfk;
}
}
also i used these JAR Files for them:
commons-codec 1.15
commons-collections4-4.4
commons-compress-1.21
commons-io-2.11.0
commons-math3-3.6.1
curvesapi-1.07
log4j-api-2.18.0
log4j-to-slf4j-2.8.2
poi-5.2.3
poi-ooxml-5.2.3
poi-ooxml-lite-5.2.3
slf4j-api-1.7.5
slf4j-simple-1.6.4
SparseBitSet-1.2
xmlbeans-5.1.1

Related

How can I make flash cards using Stacks and Queue in java

I am not sure how to implement stacks and Queues can you tell me if this class implements it in the right way. As it will perform LIFO and FIFO because it runs fine but I just wanna make sure. And can you also tell me the difference between implementing it with arraylist vs stacks and queues. Thank you
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Deck {
private File file;
private String fileName = "Untitled";
private boolean Modified;
private boolean TestRunning;
private int numCorrect;
private int numWrong;
static Queue<QuizCard> quizCardList = new LinkedList<>();
static Queue<QuizCard> quizCardList2 = new LinkedList<>();
static int curr_size;
Deck()
{
curr_size = 0;
}
static void push(int x)
{
curr_size++;
quizCardList.add((QuizCard) quizCardList);
while (!quizCardList.isEmpty())
{
quizCardList.add(quizCardList.peek());
quizCardList2.remove();
}
// swap the names of two queues
Queue<QuizCard> q = quizCardList;
quizCardList = quizCardList2;
quizCardList2 = q;
}
static void pop(){
if (quizCardList.isEmpty())
return ;
quizCardList.remove();
curr_size--;
}
static QuizCard top()
{
if (quizCardList.isEmpty())
// return -1;
return quizCardList.peek();
return null;
}
static int size()
{
return curr_size;
}
/** addQuizCard - creates and adds a QuizCard to quizCardList */
void addQuizCard(String q, String a){
if(q.length() == 0){
q = " ";
}
if(a.length() == 0){
a = " ";
}
quizCardList.add(new QuizCard(q, a));
}
/** readFile - loads in the data from a saved deck into quizCardList */
void readFile(String fileLocation){
file = new File(fileLocation);
setFileName(file.getName());
assert file.canRead();
try(BufferedReader input = new BufferedReader(new FileReader(file))){
int letterNumber;
StringBuilder dataToParse = new StringBuilder();
while((letterNumber = input.read()) != -1){
dataToParse.append((char) letterNumber);
}
}catch(IOException ioEx){
ioEx.printStackTrace();
}
}
void save(String fileLocation){
file = new File(fileLocation);
assert file.canWrite();
try (BufferedWriter output = new BufferedWriter(new FileWriter(file))) {
for(QuizCard quizCard : quizCardList){
}
}catch(IOException ioEx){
ioEx.printStackTrace();
}
}
void shuffle(){
Collections.shuffle((List<?>) quizCardList);
}
String getFileLocation(){
return file.getAbsolutePath();
}
String getFileName(){
return fileName;
}
boolean getIsModified(){
return Modified;
}
boolean getIsTestRunning(){
return TestRunning;
}
int getNumCorrect(){
return numCorrect;
}
int getNumWrong(){
return numWrong;
}
List<QuizCard> getQuizCardList(){
return (List<QuizCard>) quizCardList;
}
void setFileName(String fileName) {
if(fileName.contains(".")){
fileName = fileName.split("\\.")[0];
}
this.fileName = fileName;
}
void setIsModified(boolean newValue){
Modified = newValue;
}
void setIsTestRunning(boolean newValue){
TestRunning = newValue;
}
void setNumCorrect(int newValue){
numCorrect = newValue;
}
void setNumWrong(int newValue){
numWrong = newValue;
}
}

Parameterized runner class with 2 arguments in constructor

I wish to use a Parameterized Junit class to read from a .csv file. I want to:-
Read a 'placeID' (a String) and append it to a base url to form a webpage
Assert that the Place name 'name' (a String) is as I expect it to be for the place
The tab delimited .csv file contains 2 records as follows (will have 100's records eventually):
132
The Big House
I'm currently getting an Illegal argument exception. What's a slicker way of achieving this? I guess having the relative URL and then test data in seperate files would be better.
My code:
#RunWith(Parameterized.class)
public class PlaceTest {
public static WebDriver driver;
private String placeId;
private String name;
private PropertyPage propertyPage;
public PlaceTest(String page, String name) {
this.placeId = page;
this.name = name;
}
#Parameterized.Parameters
public static Collection data() {
return csvFileAsCollectionOfStringArrays(
System.getProperty("user.dir") +
"/src/test/resources/" +
"place_ids.csv");
}
private static Collection<String[]> csvFileAsCollectionOfStringArrays(String csvFileName) {
List<String[]> csvRows = new ArrayList<String[]>();
String rawCSVRow;
BufferedReader csvFileReader = null;
String delimiter = "\t";
System.out.println("Reading data from " + csvFileName);
try {
csvFileReader = new BufferedReader(new FileReader(csvFileName));
} catch (FileNotFoundException e) {
System.out.println("Could not find file " + csvFileName);
e.printStackTrace();
}
int rowNumber = 1;
try {
if (csvFileReader != null) {
while ((rawCSVRow = csvFileReader.readLine()) != null) {
String delimitedItems[] = rawCSVRow.split(delimiter);
csvRows.add(delimitedItems);
rowNumber++;
}
}
} catch (IOException e) {
System.out.println("Error reading row number " + rowNumber);
e.printStackTrace();
}
try {
assert csvFileReader != null;
csvFileReader.close();
} catch (IOException e) {
System.out.println("Error closing file " + e.getMessage());
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return csvRows;
}
#BeforeClass
public static void startDriver() {
driver = Driver.get();
}
#Before
public void getNextPage() {
propertyPage = new PropertyPage(driver);
driver.get(TestWebApp.getURL() + this.placeId);
}
#Test
public void checkNamePresent() {
WebElement placeName = propertyPage.checkName();
assertEquals("Expected match on name", this.name, placeName.getText());
}
#AfterClass
public static void quitDriver() {
driver.quit();
}
}
Try this:
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import au.com.bytecode.opencsv.CSVReader;
#RunWith(Parameterized.class)
public class PlaceTest {
private String placeId;
private String name;
public PlaceTest(String page, String name) {
this.placeId = page;
this.name = name;
}
#Parameterized.Parameters
public static Collection<String[]> data() {
CSVReader reader = new CSVReader(new InputStreamReader(PlaceTest.class.getResourceAsStream("place_ids.csv")));
List<String[]> lines;
try {
lines = reader.readAll();
return lines;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new ArrayList<String[]>();
}
#Test
public void checkNamePresent() {
System.out.println(this.placeId + " " + this.name);
}
}
The place_ids.csv has to be in: \src\test\resources\<your package>\place_ids.csv
Update your pom with CSVReader dependency:
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.3</version>
</dependency>
Update:
csv file:
132, Some text
133, Other text
Your example above has one word per line. The code above was compile and tested.

Trying to read a text file using regex to check each line

I am trying to write a program that will allow a user to input a name of a movie and the program would then generate the date associated with. I have a text file that has date and the movies that pertain to it. I am reading the file via Scanner and I created a movie class that stores an ArrayList and String for movies and date, respectively. I am having trouble with reading the files. Can anyone please assist me. Thank you!
Here is a part of the text file:
10/1/2014
Der Anstandige
"Men, Women and Children"
Nas: Time is Illmatic
10/2/2014
Bang Bang
Haider
10/3/2014
Annabelle
Bitter Honey
Breakup Buddies
La chambre bleue
Drive Hard
Gone Girl
The Good Lie
A Good Marriage
The Hero of Color City
Inner Demons
Left Behind
Libertador
The Supreme Price
Here is my movie class
import java.util.ArrayList;
public class movie
{
private ArrayList<String> movies;
private String date;
public movie(ArrayList<String> movies, String date)
{
this.movies = movies;
this.date = date;
}
public String getDate()
{
return date;
}
public void setDate(String date)
{
this.date = date;
}
public ArrayList<String> getMovies()
{
return movies;
}
}
Here is the readFile class
package Read;
import java.util.List;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class readFile
{
public static List<movie> movies;
public static String realPath;
public static ArrayList<String> mov;
public static String j;
public static String i;
public static void main(String[]args)
{
//movies = new ArrayList<movie>();
realPath = "movie_release_dates.txt";
File f = new File(realPath);
try
{
String regex1 = "[^(0-9).+]";
String regex2 = "[^0-9$]";
Scanner sc = new Scanner(f);
while (sc.hasNextLine())
{
System.out.println("Hello");
//movies
if(!sc.nextLine().matches(regex2))
{
i = sc.nextLine();
System.out.println("Hello2");
System.out.println(i);
}
//date
while(sc.nextLine().matches(regex1))
{
System.out.println("Hello3");
if(!sc.nextLine().matches(regex1))
{
j = sc.nextLine();
mov.add(sc.nextLine());
System.out.println("Hello4");
}
}
movie movie = new movie(mov,i);
movies.add(movie);
}
// sc.close();
}
catch(Exception e)
{
System.out.println("CANT");
}
}
}
You shouldn't be calling sc.nextLine () in every check. Every NextLine () call reads next line.This means that you are checking one line and processing next line
package com.stackoverflow.q26269799;
import java.util.List;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadFile {
public static List<Movie> movies = new ArrayList<Movie>();
public static String realPath;
public static ArrayList<String> mov;
public static String j;
public static String i;
public static void main(String[] args) {
//movies = new ArrayList<movie>();
realPath = "movie_release_dates.txt";
File f = new File(realPath);
if ( !f.exists()) {
System.err.println("file path not specified");
}
try {
String regex1 = "[^(0-9).+]";
String regex2 = "[^0-9$]";
Scanner sc = new Scanner(f);
while (sc.hasNextLine()) {
System.out.println("Hello");
// movies
String nextLine = sc.nextLine();
if (nextLine != null) {
if ( !nextLine.matches(regex2)) {
i = nextLine;
System.out.println("Hello2");
System.out.println(i);
}
// date
while (nextLine != null && nextLine.matches(regex1)) {
System.out.println("Hello3");
if ( !nextLine.matches(regex1)) {
j = nextLine;
mov.add(nextLine);
System.out.println("Hello4");
}
nextLine = sc.nextLine();
}
}
Movie movie = new Movie(mov, i);
movies.add(movie);
}
// sc.close();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
This is needed: //movies = new ArrayList<movie>();
Every time you call nextLine it will move the scanner point to the next line. So call it once a time and check if it match those regex. String nextLine = sc.nextLine();
Please check you whether the file path is specified.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class ReadFile
{
Map<String, String> movies;
public static void main(String[] args) throws IOException
{
ReadFile readFile = new ReadFile();
readFile.movies = new TreeMap<>();
try
{
readFile.importData();
printf(readFile.queryData("Der Anstandige"));
printf(readFile.queryData("Bitter"));
printf(readFile.queryData("blah"));
printf(readFile.queryData("the"));
}
catch(IOException e)
{
throw(e);
}
}
void importData() throws IOException, FileNotFoundException
{
LineNumberReader reader = null;
File file = new File("c:/movie_release_dates.txt");
try
{
reader = new LineNumberReader(new FileReader(file), 1024*64); //
String line;
String date = null, movie = null;
while((line = reader.readLine()) != null)
{
line = line.trim();
if(line.equals("")) continue;
if(line.matches(PATTERN_DATE))
{
date = line;
date = strf("%s/%s",
date.substring(date.length() - 4),
date.substring(0, date.length() - 5));
continue;
}
else
{
movie = line.trim();
}
movies.put(movie, date);
}
}
catch(FileNotFoundException e)
{
throw(e);
}
finally
{
reader.close();
}
}
String queryData(String title)
{
String regex = "(?i)" + title.replaceAll("\\s", "\\s+");
String[] matches = new String[movies.size()];
int i = 0; for(Entry<String , String> movie : movies.entrySet())
{
String key = movie.getKey();
String val = movie.getValue();
if(key.matches(regex))
{
matches[i++] = strf("{movie=%s, date=%s}", key, val);
}
else if(key.toUpperCase().trim()
.contains(title.toUpperCase().trim()))
{
matches[i++] = strf("{movie=%s, date=%s}", key, val);
}
}
String string = "";
if(matches[0] == null)
{
string = "Not found\n";
}
else
{
i = 0; while(matches[i] != null)
{
string += matches[i++] + "\n";
}
}
return string;
}
final String strf(String arg0, Object ... arg1)
{
return String.format(arg0, arg1);
}
final static void printf(String format, Object ... args)
{
System.out.printf(format, args);
}
final static void println(String x)
{
System.out.println(x);
}
final String PATTERN_DATE = "\\d{1,2}\\/\\d{1,2}\\/\\d{4}";
}
Console output:
{movie=Der Anstandige, date=2014/10/1}
{movie=Bitter Honey, date=2014/10/3}
Not found
{movie=The Good Lie, date=2014/10/3}
{movie=The Hero of Color City, date=2014/10/3}
{movie=The Supreme Price, date=2014/10/3}

Selenium with Java and TestNG - Test login with Excel DataSheet

Create 2 Classes (DataProviderWithExcel, ExcelUtils) and export the login details (User Name, Password). But it skipped"Registration_data" in the "DataProviderWithExcel" Class.
DataProviderWithExcel Class
package practiceTestCases;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import utility.ExcelUtils;
public class DataProviderWithExcel {
WebDriver driver;
private String sTestCaseName;
private int iTestCaseRow;
#BeforeClass
public void beforeMethod() throws Exception {
System.setProperty("webdriver.chrome.driver","E://chromedriver.exe");
driver=new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.store.demoqa.com");
}
#Test(dataProvider="Authentication")
public void Registration_data(String sUserName,String sPassword)throws Exception{
driver.findElement(By.xpath(".//*[#id='account']/a")).click();
driver.findElement(By.id("log")).sendKeys(sUserName);
System.out.println(sUserName);
driver.findElement(By.id("pwd")).sendKeys(sPassword);
System.out.println(sPassword);
driver.findElement(By.id("login")).click();
System.out.println(" Login Successfully, now it is the time to Log Off buddy.");
driver.findElement(By.xpath(".//*[#id='account_logout']/a")).click();
}
#DataProvider()
public Object[][] Authentication() throws Exception{
ExcelUtils.setExcelFile("E://My Work Place//Excel//src//testData//TestData.xlsx","Sheet1");
sTestCaseName = this.toString();
sTestCaseName = ExcelUtils.getTestCaseName(this.toString());
iTestCaseRow = ExcelUtils.getRowContains(sTestCaseName,0);
Object[][] testObjArray = ExcelUtils.getTableArray("E://My Work Place//Excel//src//testData//TestData.xlsx//TestData.xlsx","Sheet1",iTestCaseRow);
return (testObjArray);
}
#AfterClass
public void afterMethod() {
driver.close();
}
}
ExcelUtils Class
package utility;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
public static void setExcelFile(String Path,String SheetName) throws Exception {
try {
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e){
throw (e);
}
}
public static Object[][] getTableArray(String FilePath, String SheetName, int iTestCaseRow) throws Exception
{
String[][] tabArray = null;
try{
FileInputStream ExcelFile = new FileInputStream(FilePath);
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int startCol = 1;
int ci=0,cj=0;
int totalRows = 1;
int totalCols = 2;
tabArray=new String[totalRows][totalCols];
for (int j=startCol;j<=totalCols;j++, cj++)
{
tabArray[ci][cj]=getCellData(iTestCaseRow,j);
System.out.println(tabArray[ci][cj]);
}
}
catch (FileNotFoundException e)
{
System.out.println("Could not read the Excel sheet");
e.printStackTrace();
}
catch (IOException e)
{
System.out.println("Could not read the Excel sheet");
e.printStackTrace();
}
return(tabArray);
}
public static String getCellData(int RowNum, int ColNum) throws Exception{
try{
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
}catch (Exception e){
return"";
}
}
public static String getTestCaseName(String sTestCase)throws Exception{
String value = sTestCase;
try{
int posi = value.indexOf("#");
value = value.substring(0, posi);
posi = value.lastIndexOf(".");
value = value.substring(posi + 1);
return value;
}catch (Exception e){
throw (e);
}
}
public static int getRowContains(String sTestCaseName, int colNum) throws Exception{
int i;
try {
int rowCount = ExcelUtils.getRowUsed();
for ( i=0 ; i<rowCount; i++){
if (ExcelUtils.getCellData(i,colNum).equalsIgnoreCase(sTestCaseName)){
break;
}
}
return i;
}catch (Exception e){
throw(e);
}
}
public static int getRowUsed() throws Exception {
try{
int RowCount = ExcelWSheet.getLastRowNum();
return RowCount;
}catch (Exception e){
System.out.println(e.getMessage());
throw (e);
}
}
}
Error
SKIPPED: Registration_data
java.lang.RuntimeException: java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException
at org.testng.internal.MethodInvocationHelper.invokeDataProvider(MethodInvocationHelper.java:161)
at org.testng.internal.Parameters.handleParameters(Parameters.java:429)
at org.testng.internal.Invoker.handleParameters(Invoker.java:1383)
You are missing a jar file or its dependency, if you are using POM.xml then add the below dependencies to the POM file
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
If not then download poi.jar v3.9 and poi-ooxml v3.9 from Apache POI site and add it to the class path of the project

Exception reading XLSB File Apache POI java.io.CharConversionException

Im developing a Java aplication that reads an excel xlsb file using Apache POI, but I got an exception while reading it, my code is as follows:
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.Package;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import java.util.Iterator;
public class Prueba {
public static void main (String [] args){
String direccion = "C:/Documents and Settings/RSalasL/My Documents/New Folder/masstigeoct12.xlsb";
Package pkg;
try {
pkg = Package.open(direccion);
XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
Iterator<InputStream> sheets = r.getSheetsData();
while(sheets.hasNext()) {
System.out.println("Processing new sheet:\n");
InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet);
parser.parse(sheetSource);
sheet.close();
System.out.println("");
}
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OpenXML4JException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void processAllSheets(String filename) throws Exception {
Package pkg = Package.open(filename);
XSSFReader r = new XSSFReader( pkg );
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
Iterator<InputStream> sheets = r.getSheetsData();
while(sheets.hasNext()) {
System.out.println("Processing new sheet:\n");
InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet);
parser.parse(sheetSource);
sheet.close();
System.out.println("");
}
}
public static XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
XMLReader parser =
XMLReaderFactory.createXMLReader(
"org.apache.xerces.parsers.SAXParser"
);
ContentHandler handler = new SheetHandler(sst);
parser.setContentHandler(handler);
return parser;
}
private static class SheetHandler extends DefaultHandler {
private SharedStringsTable sst;
private String lastContents;
private boolean nextIsString;
private SheetHandler(SharedStringsTable sst) {
this.sst = sst;
}
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
// c => cell
if(name.equals("c")) {
// Print the cell reference
System.out.print(attributes.getValue("r") + " - ");
// Figure out if the value is an index in the SST
String cellType = attributes.getValue("t");
if(cellType != null && cellType.equals("s")) {
nextIsString = true;
} else {
nextIsString = false;
}
}
// Clear contents cache
lastContents = "";
}
public void endElement(String uri, String localName, String name)
throws SAXException {
// Process the last contents as required.
// Do now, as characters() may be called more than once
if(nextIsString) {
int idx = Integer.parseInt(lastContents);
lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
nextIsString = false;
}
// v => contents of a cell
// Output after we've seen the string contents
if(name.equals("v")) {
System.out.println(lastContents);
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
lastContents += new String(ch, start, length);
}
}
}
And the exception is this:
java.io.CharConversionException: Characters larger than 4 bytes are not supported: byte 0x83 implies a length of more than 4 bytes
at org.apache.xmlbeans.impl.piccolo.xml.UTF8XMLDecoder.decode(UTF8XMLDecoder.java:162)
at org.apache.xmlbeans.impl.piccolo.xml.XMLStreamReader$FastStreamDecoder.read(XMLStreamReader.java:762)
at org.apache.xmlbeans.impl.piccolo.xml.XMLStreamReader.read(XMLStreamReader.java:162)
at org.apache.xmlbeans.impl.piccolo.xml.PiccoloLexer.yy_refill(PiccoloLexer.java:3474)
at org.apache.xmlbeans.impl.piccolo.xml.PiccoloLexer.yylex(PiccoloLexer.java:3958)
at org.apache.xmlbeans.impl.piccolo.xml.Piccolo.yylex(Piccolo.java:1290)
at org.apache.xmlbeans.impl.piccolo.xml.Piccolo.yyparse(Piccolo.java:1400)
at org.apache.xmlbeans.impl.piccolo.xml.Piccolo.parse(Piccolo.java:714)
at org.apache.xmlbeans.impl.store.Locale$SaxLoader.load(Locale.java:3439)
at org.apache.xmlbeans.impl.store.Locale.parseToXmlObject(Locale.java:1270)
at org.apache.xmlbeans.impl.store.Locale.parseToXmlObject(Locale.java:1257)
at org.apache.xmlbeans.impl.schema.SchemaTypeLoaderBase.parse(SchemaTypeLoaderBase.java:345)
at org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument$Factory.parse(Unknown Source)
at org.apache.poi.xssf.eventusermodel.XSSFReader$SheetIterator.<init>(XSSFReader.java:207)
at org.apache.poi.xssf.eventusermodel.XSSFReader$SheetIterator.<init>(XSSFReader.java:166)
at org.apache.poi.xssf.eventusermodel.XSSFReader.getSheetsData(XSSFReader.java:160)
at EDManager.Prueba.main(Prueba.java:36)
The file has 2 sheets, one with 329 rows and 3 columns and the other with 566 rows and 3 columns, I just want to read the file to find if a value is in the second sheet.
Apache POI doesn't support the .xlsb file format for anything other than text extraction. Apache POI will happily provide full read or write support .xls files (via HSSF) and .xlsx files (via XSSF), or both (via the common SS UserModel interface).
However, the .xlsb format is not supported for generatl operations - it's a very odd hybrid between the two, and the large amount of work involved has meant no-one has been willing to volunteer/sponsor the work required.
What Apache POI does offer for .xlsb, as of Apache POI 3.15 beta3 / 3.16, is a text extractor for .xlsb files - XSSFBEventBasedExcelExtractor. You can use that to get the text out of your file, or with a few tweaks convert it to something like CSV
For full read/write support, you'll need to convert your file to either .xls (if it doesn't have very large numbers of rows/columns), or .xlsx (if it does). If you're really really keen to help though, you could review the source code for XSSFBEventBasedExcelExtractor, then have a go at contributing patches to add full support to POI for it!
(Additionally, I think from the exception that your particular .xlsb file is partly corrupt, but even if it wasn't it still wouldn't be supported by Apache POI for anything other than text extraction, sorry)
I have tried reading XLSB file using Apache POI and it is successful. Below is the code snippet I have used.
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.binary.XSSFBSharedStringsTable;
import org.apache.poi.xssf.binary.XSSFBSheetHandler;
import org.apache.poi.xssf.binary.XSSFBStylesTable;
import org.apache.poi.xssf.eventusermodel.XSSFBReader;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class ApachePoiXLSB {
public static void main (String [] args){
String xlsbFileName = "test.xlsb";
OPCPackage pkg;
try {
pkg = OPCPackage.open(xlsbFileName);
XSSFBReader r = new XSSFBReader(pkg);
XSSFBSharedStringsTable sst = new XSSFBSharedStringsTable(pkg);
XSSFBStylesTable xssfbStylesTable = r.getXSSFBStylesTable();
XSSFBReader.SheetIterator it = (XSSFBReader.SheetIterator) r.getSheetsData();
List<String> sheetTexts = new ArrayList<>();
while (it.hasNext()) {
InputStream is = it.next();
String name = it.getSheetName();
TestSheetHandler testSheetHandler = new TestSheetHandler();
testSheetHandler.startSheet(name);
XSSFBSheetHandler sheetHandler = new XSSFBSheetHandler(is,
xssfbStylesTable,
it.getXSSFBSheetComments(),
sst, testSheetHandler,
new DataFormatter(),
false);
sheetHandler.parse();
testSheetHandler.endSheet();
sheetTexts.add(testSheetHandler.toString());
}
System.out.println("output text:"+sheetTexts);
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OpenXML4JException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.usermodel.XSSFComment;
class TestSheetHandler implements XSSFSheetXMLHandler.SheetContentsHandler {
private final StringBuilder sb = new StringBuilder();
public void startSheet(String sheetName) {
sb.append("<sheet name=\"").append(sheetName).append(">");
}
public void endSheet() {
sb.append("</sheet>");
}
#Override
public void startRow(int rowNum) {
sb.append("\n<tr num=\"").append(rowNum).append(">");
}
#Override
public void endRow(int rowNum) {
sb.append("\n</tr num=\"").append(rowNum).append(">");
}
#Override
public void cell(String cellReference, String formattedValue, XSSFComment comment) {
formattedValue = (formattedValue == null) ? "" : formattedValue;
if (comment == null) {
sb.append("\n\t<td ref=\"").append(cellReference).append("\">").append(formattedValue).append("</td>");
} else {
sb.append("\n\t<td ref=\"").append(cellReference).append("\">")
.append(formattedValue)
.append("<span type=\"comment\" author=\"")
.append(comment.getAuthor()).append("\">")
.append(comment.getString().toString().trim()).append("</span>")
.append("</td>");
}
}
#Override
public void headerFooter(String text, boolean isHeader, String tagName) {
if (isHeader) {
sb.append("<header tagName=\"").append(tagName).append("\">").append(text).append("</header>");
} else {
sb.append("<footer tagName=\"").append(tagName).append("\">").append(text).append("</footer>");
}
}
#Override
public String toString() {
return sb.toString();
}
}
I have a implementation using the smartxls, and my code firts convert the xlsb to xlsx and after can use ApachePoi. The next method receive a java.io.File and verify if its extension is xlsb and convert this to xlsx and replace file whit the new. This works for me.
private void processXLSBFile(File file) {
WorkBook workBook = new WorkBook();
String filePath = file.getAbsolutePath();
if (FilenameUtils.getExtension(filePath).equalsIgnoreCase((Static.XLSB_EXT))) {
try {
workBook.readXLSB(new java.io.FileInputStream(filePath));
filePath = filePath.replaceAll("(?i)".concat(Static.XLSB),
Static.XLSX_EXT.toLowerCase());
workBook.writeXLSX(new java.io.FileOutputStream(filePath));
final File xlsb = new File(filePath);
file = xlsb;
} catch (Exception e) {
logger.error(e.getMessage(), e);
MensajesJSFUtil
.mostrarMensajeNegocio(new GTMException(e, ClaveMensaje.COMANDAS_ADJUNTAR_XLSBFILE_READERROR));
}
}
}

Categories