cannot get a numerical value from the excel cell - java

public Object[][] dataProviderMethod() throws IOException {
try {
file = new FileInputStream(new File("/Users/nanthakumar/Documents/workspace/Myna_Admin/src/com/myna/testdata/login.xls"));
workbook = new HSSFWorkbook(file);
sheet = workbook.getSheetAt(0);
row = sheet.getLastRowNum() + 1;
col = sheet.getRow(0).getLastCellNum();
data = new String[row][col];
for (i = 0; i < row; i++) {
rowvalue = sheet.getRow(i);
for (j = 0; j < col; j++) {
cellValue = rowvalue.getCell(j);
data[i][j] = cellValue.getStringCellValue();
System.out.println("The value is ----->" + data[i][j]);
}
workbook.close();
file.close();
}
} catch (FileNotFoundException nana) {
nana.printStackTrace();
}
return data;
}
This is my code and I tried to add the getnumericalCellvalue() instead of getStringCellValue() but that is not working for me.

first you have to check in the template excel whether the column is number or text.you can get the numerical value if and only if the column is of type number.so change the template excel and try

Related

how to read and validate blank lines from selenium excel

here in my code I am trying to read only the data from column "A" . Here in the screen shot I have attached how the sample data looks like. I am having an issue while reading the contents as its throwing null pointer exception because of the blank line. I need to verify the blank line as well . Please give me your thoughts
public void verifyAllSupportingLogs() throws Exception {
Sheet sheet = getFilenameSupportingLogs("c:\\DataFile");
int rowCount = sheet.getPhysicalNumberOfRows();
XSSFCell firstColumnCell = null;
int firstColumnRowCount = 0;
ArrayList<String> InnerArray = new ArrayList<>();
String cellValues = null;
String GetsupportingLogs1 = null;
for (int i = 0; i < rowCount; i++) {
try {
XSSFRow row = (XSSFRow) sheet.getRow(i);
firstColumnCell = row.getCell(0);
} catch (NullPointerException nullPointerException) {
System.out.println("Cell is null at index: " + i);
}
if (firstColumnCell != null) {
if (firstColumnCell.getStringCellValue().length() > 0) {
firstColumnRowCount = i;
}
}
}
for (int j = 0; j <= firstColumnRowCount; j++) {
XSSFRow row = (XSSFRow) sheet.getRow(j);
XSSFCell cell = row.getCell(0);
String valuesFromExcel = cell.getStringCellValue();
InnerArray.add(valuesFromExcel);
cellValues = InnerArray.toString();
}
String GetsupportingLogs = con.clickOnSupportingLogsTextbox(GetsupportingLogs1);
System.out.println("GetsupportingLogs" + GetsupportingLogs);
con.checkValueSupportingLogs(cellValues, GetsupportingLogs);
}
public void checkValueSupportingLogs(String GetsupportingLogs, String cellValue) throws Exception {
java.lang.String[] cellValue1 = cellValue.split("\n");
for (String cellValue2 : cellValue1) {
if (GetsupportingLogs.contains(cellValue2)) {
System.out.println("Success, this string is in the supporting logs.");
} else {
reportFailure("ERROR! This string is not in the supporting logs.");
}
}
}
Simply apply same check if cell is null.
Instead of:
for (int j = 0; j <= firstColumnRowCount; j++) {
XSSFRow row = (XSSFRow) sheet.getRow(j);
XSSFCell cell = row.getCell(0);
String valuesFromExcel = cell.getStringCellValue();
InnerArray.add(valuesFromExcel);
cellValues = InnerArray.toString();
}
use this:
XSSFCell cell = null;
for (int j = 0; j <= firstColumnRowCount; j++) {
XSSFRow row = (XSSFRow) sheet.getRow(j);
try {
cell = row.getCell(0);
}
catch (NullPointerException nullPointerException) {
System.out.println("Cell is null at index: " + j);
}
if (cell != null) {
String valuesFromExcel = cell.getStringCellValue();
InnerArray.add(valuesFromExcel);
cellValues = InnerArray.toString();
cell = null;
}
}
In case if different data types in the excel file, you can combine with this: Error : Cannot get a STRING value from a NUMERIC cell in Selenium

How to Set/Insert text/value in Excel using Apache Poi

This method will take a String value for the name to search and return the address for the first record found in the column next to it, assuming that the name is in the first column and the address is in the second column. It will iterate over all sheets as asked. How can i change/enhance this code to Insert/Set value/Text in the third column?
public static String findAddressByName(String nameToSearch) {
String fileLocation = "I:\\foo.xlsx";
XSSFWorkbook wb = new XSSFWorkbook(new File(fileLocation));
for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
XSSFSheet sheet = wb.getSheetAt(sheetIndex);
for (int rowIndex = 0; rowIndex < sheet.getLastRowNum(); rowIndex++) {
XSSFRow row = sheet.getRow(rowIndex);
if (row != null && row.getCell(0).getStringCellValue().equals(nameToSearch)) {
return row.getCell(1).getRawValue();
}
}
}
return "";
}

upload large .xlsx file in gui java

i have a large excel file containing 600.000 rows , i used XSSFWorkbook to upload the excel file at a Jtable in my GUI but it takes about 15 minutes to be done in eclipse and once i export my project to a jar file i can't do it even in the 15 minutes . Any help please ?
Here is the method , that i found in internet to upload my excel file .
void fillData(File file) {
int index = -1;
XSSFWorkbook workbook = null;
try {
try {
String f = file.getPath();
File file1 = new File(f);
OPCPackage opcPackage = OPCPackage.open(file1);
workbook = new XSSFWorkbook(opcPackage);
} catch (IOException ex) {
Logger.getLogger(ProjectApp3.class.getName()).log(Level.SEVERE, null, ex);
}
String[] strs = new String[workbook.getNumberOfSheets()];
//get all sheet names from selected workbook
for (int i = 0; i < strs.length; i++) {
strs[i] = workbook.getSheetName(i);
}
JFrame frame = new JFrame("Input Dialog");
//select sheet
String selectedsheet = (String) JOptionPane.showInputDialog(
frame, "Which worksheet you want to import ?", "Select Worksheet",
JOptionPane.QUESTION_MESSAGE, null, strs, strs[0]);
if (selectedsheet != null) {
for (int i = 0; i < strs.length; i++) {
if (workbook.getSheetName(i).equalsIgnoreCase(selectedsheet))
index = i;
}
XSSFSheet sheet = workbook.getSheetAt(index);
XSSFRow row = sheet.getRow(0);
//import headers data
headers.clear();
for (int i = 0; i < row.getLastCellNum(); i++) {
XSSFCell cell1 = row.getCell(i);
headers.add(cell1.toString());
}
//import data
data1.clear();
for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
Vector d = new Vector();
row = sheet.getRow(j);
int noofrows = row.getLastCellNum();
for (int i = 0; i < noofrows; i++) { //To handle empty excel cells
XSSFCell cell = row.getCell(i,
org.apache.poi.ss.usermodel.Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
d.add(cell.toString());
}
d.add("\n");
data1.add(d);
}
} else {
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
I think the basic problem is that you're trying to give. your Jtable all the data at startup. This is going to be deeply problematic. You may want to write a custom subclass from AbstractTableModel. See the docs for Jtable that includes this:
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() { return 10; }
public int getRowCount() { return 10;}
public Object getValueAt(int row, int col) { return new Integer(row*col); }
};
JTable table = new JTable(dataModel);
JScrollPane scrollpane = new JScrollPane(table);
You can implement those three methods based on the info that POI gives you. But do lazy loading of the data, most especially for getValueAt(). Keep the spreadsheet file open and grab the data only when the user scrolls to view it.

getting data by column name apache poi excel

I am using apache POI for excel import and parsing .
I have to get the data by passing column name .
this is my code
JSONObject jo = new JSONObject();
JSONArray dataCollection = new JSONArray();
JSONObject data = null;
try {
String tempCampaignFilesPath = getSessionData("userPath") + System.getProperty("file.separator") + "tempCampaignFiles";
File someFile = new File(tempCampaignFilesPath, fileName);
/* read from this file */
FileInputStream fileInputStream = new FileInputStream(someFile);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet sheet = workbook.getSheet(sheetName);
int rowNum = sheet.getLastRowNum() + 1;
int colNum = sheet.getRow(0).getLastCellNum();
Row row = null;
Cell cell = null;
for (int i = 1; i < rowNum; i++) {
row = sheet.getRow(i);
data = new JSONObject();
for (int j = 0; j < colNum; j++) {
cell = row.getCell(j);
data.put(columnList.get(j), cellToString(cell));
}
dataCollection.put(data);
}
fileInputStream.close();
// someFile.delete();
jo.put("tableData", dataCollection);
} catch (Exception e) {
e.printStackTrace();
}
return jo;
There is a provision for column index but how could I do it by column name.
Please help me.
You have to convert column name to index:
int colIdx = CellReference.convertColStringToIndex(letter);
CellUtil.getCell(row, colIdx)
or if you need convert column index to string:
String colName = CellReference.convertNumToColString(colIdx)
Please find below the code an another workaround for this .Please see the comments in code to be more clear what I have done.
JSONObject jo = new JSONObject();
JSONArray dataCollection = new JSONArray();
JSONObject data = null;
try {
String tempCampaignFilesPath = getSessionData("userPath") + System.getProperty("file.separator") + "tempCampaignFiles";
File someFile = new File(tempCampaignFilesPath, fileName);
/* read from this file */
FileInputStream fileInputStream = new FileInputStream(someFile);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet sheet = workbook.getSheet(sheetName);
int rowNum = sheet.getLastRowNum() + 1;
int colNum = sheet.getRow(0).getLastCellNum();
Row row = null;
Cell cell = null;
/* first row data for column names and index */
Map<String, Integer> colMapByName = new HashMap<String, Integer>();
if (sheet.getRow(0).cellIterator().hasNext()) {
for (int j = 0; j < colNum; j++) {
colMapByName.put(cellToString(sheet.getRow(0).getCell(j)), j);
}
}
System.out.println(colMapByName);//shows the indexes of columns populated by traversing first row
/* first row data */
for (int i = 1; i < rowNum; i++) {
row = sheet.getRow(i);
data = new JSONObject();
//colMap consists the columnnames and alias name for it
for (Entry<String, String> colData : colMap.entrySet()) {
cell = row.getCell(colMapByName.get(colData.getValue()));//gives the index of column from colMapByName Map by passing column name
data.put(colData.getKey(), cellToString(cell));//now the data passed to the alias for the column tobe used in application
}
dataCollection.put(data);
}
fileInputStream.close();
someFile.delete();
jo.put("tableData", dataCollection);
} catch (Exception e) {
e.printStackTrace();
}
return jo;

Workbook library does not read the cell value if the cell is empty

Hi I am reading Excel file from java using jxl workbook library.Below is the code.
Workbook wb = Workbook.getWorkbook(new File(destFile));
String line = ""; // available
for (int sheetNo = 0; sheetNo < wb.getNumberOfSheets(); sheetNo++) {
Sheet sheet = wb.getSheet(sheetNo);
System.out.println("Sheet Name is:\t" + sheet.getName());
if(sheet.getName().trim().equals("Store List")){
int columns = sheet.getColumns();
int rows = sheet.getRows();
String data;
for (int row = 0; row < rows; row++) {
for (int col = 1; col < columns; col++) {
data = sheet.getCell(col, row).getContents();
line = line + data + "#";
}
line += "#&#";
}
System.out.println("Entire line is" + line);
}
}
The above code reads row&column data from the excel file and passes it to the service method for further processing.
When I traverse it line-by-line for the empty cell, the Java code throws IndexOutOfBoundException. Please find the java code below which throws exception.
for(int elementCount=4;elementCount<elements.length;elementCount++) {
String strquantity = rowValues[elementCount];
int quantity=0;
if(strquantity.equals("")){
quantity = 0;
} else {
quantity = Integer.parseInt(strquantity);
System.out.println("Quantity value is:\t" + quantity);
}
}
As you the above code exception is thrown at line 2.
I believe that cause is due to workbook library.
After doing some rnd i got the solution,If it is empty cell will get the 0 or null value from jxl API.
As in my code i was looking for empty string
if(strquantity.equals("")){
quantity = 0;
}
now the code changed to below one
if(strquantity.equals(null) || strquantity.equals("0")){
quantity = 0;
}

Categories