Reading all dropdown options from .xlsx sheet - java

I have a dropdown in an Excel(.xlxs) and I want to get all its options in a list.
I tried using the below code, but I didn't get any data.
public String[] getCellDropdownValues() {
List<XSSFDataValidation> dataValidations = (List<XSSFDataValidation>) sheet.getDataValidations();
Iterator<XSSFDataValidation> iterator = dataValidations.iterator();
XSSFDataValidation dataValidation = iterator.next();
String[] explicitListValues = dataValidation.getValidationConstraint().getExplicitListValues();
return explicitListValues;
}
Any help is appreciated.

There might be following issue with your code:
You have mentioned .xlxs, Kindly rename it with ".xlsx" (currently ".xlxs").
Verify your sheet for a valid dropdown value.
Incorrect import or you haven't mentioned the code to get the workbook and the sheet.
Imports:
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.Iterator;
import java.util.List;
Code:
public static String[] getCellDropdownValues() throws Exception {
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(System.getProperty("user.dir")+"/data.xlsx"));
XSSFSheet sheet = workbook.getSheet("Sheet1");
List<XSSFDataValidation> dataValidations = (List<XSSFDataValidation>) sheet.getDataValidations();
Iterator<XSSFDataValidation> iterator = dataValidations.iterator();
XSSFDataValidation dataValidation = iterator.next();
String[] explicitListValues = dataValidation.getValidationConstraint().getExplicitListValues();
return explicitListValues;
}
Code Output:
Note: Same code is working fine for me.

Related

how to insert data in an excel sheet into database(including blank spaces without editing them) using java

Java code to read all the cells in a sheet including blank cells in excel sheets and insert the same data into postgresql database without editing them.
I have already tried using apache-poi, missingcellpolicy, replacefunction, etc. But, it throws a nullpointerexception.
When I run my code to display the celltype of a cell in excel, it is not displaying any type for blankspaces and skips the cell completely.
Here is the code:
package poiexcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
//import java.util.ArrayList;
import java.util.Date;
//import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
#SuppressWarnings("unused")
public class ReadExcel {
public static final String SAMPLE_XLSX_FILE_PATH = "C:\\Raj's Documents\\Documents\\studentdata.xlsx";
public static void main(String[] args) throws IOException, InvalidFormatException {
try {
FileInputStream file = new FileInputStream(new File(SAMPLE_XLSX_FILE_PATH));// Read the spreadsheet that
// needs to be uploaded
XSSFWorkbook myExcelBook = new XSSFWorkbook(file);
DataFormatter dataFormatter = new DataFormatter();
for (Sheet myExcelsheet : myExcelBook) {
// ArrayList<SheetDetails> details = new ArrayList<SheetDetails>();
// for (Row row : myExcelsheet) {
for (int i = 0; i < myExcelsheet.getPhysicalNumberOfRows(); i++) {
Row row = myExcelsheet.getRow(i);
for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
Cell cell = row.getCell(j);
CellType ct = cell.getCellType();
System.out.println(ct);
}
System.out.println();
}
}
myExcelBook.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Here is the output:
NUMERIC
STRING
java.lang.NullPointerException
at poiexcel.ReadExcel.main(ReadExcel.java:52)
Under 'dependencies'in build.gradle (if using Gradle, otherwise find the matching dependency for Maven) file paste the dependency we want:
compile group: 'org.apache.commons', name: 'commons-csv', version: '1.5'
Create the following import:
import org.apache.commons.csv.*;
Parsing an excel csv file is then as easy as:
public Iterable<CSVRecord> parse(String csvPath) throws IOException {
Reader in = new FileReader(csvPath);
return CSVFormat.EXCEL.withFirstRecordAsHeader().parse(in);
}
EXCEL can be changed to DEFAULT if the csv files are plain text csv files.
We can then use the iterable list to get its values by id, column title or by enum, although these need to be defined. Then persist these values into the relevant database entity via the corresponding repository.

I am getting a error for CELL_TYPE_NUMERIC .I have Any advice?

package com.writeAndRead;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.*;
public class Read {
public static void main(String[] args) throws FileNotFoundException, IOException {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream("excel.xls"));
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
}
if (row.getCell(1).getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
System.out.println(row.getCell(1).getDateCellValue());
}
}
}
error: CELL_TYPE_NUMERIC cannot be resolved or is not a field.
I have tried reducing it to just NUMERIC but I GOT THE SAME PROBLEM.
Hey guys thanks for the comments. I solved the issue myself. The HSSFCell.CELL_TYPE_NUMERIC is now just NUMERIC. Thanks guys.
later version of Apache POI poi-4.0.1 should Change your if condition from HSSFCell.CELL_TYPE_NUMERIC to NUMERIC
like this :
if (row.getCell(1).getCellType() == NUMERIC) {
System.out.println(row.getCell(1).getDateCellValue());

get text from Excel data and click on web element Selenium radio button

Both tests work okay individually I need help merging them both.
I'm unable to test both together.
If sheet cell is read as a male it should click on the male radio button.
Please help me resolve this test
ExcelRead33.java will read the specific cell from excel sheet.
facebookradio.java will run a test on the radio button.
Excel file for data.
package testpoi;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class facebookradio {
public static void main(String[] args) throws Exception {
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://www.facebook.com");
WebElement male_radio_button=driver.findElement(By.id("u_0_a"));
male_radio_button.click();
WebElement female_radio_button=driver.findElement(By.id("u_0_9"));
female_radio_button.click();
ExcelRead33.java will read the specific cell from excel sheet.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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;
//How to read excel files using Apache POI
public class ExcelRead33 {
public static void main (String [] args) throws IOException{
FileInputStream fis = new FileInputStream("C:/DDFREAD.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(1);
//Read specific row and column
Row row = sheet.getRow(2);
Cell cell = row.getCell(8);
//This will print data which I want to click
System.out.println(cell);
Excel File
Sharpen your Core java skills ahead of learning Selenium. This is a dirty code [without leveraging OOPs] of what you're trying to perform.
FileInputStream fis = new FileInputStream(System.getProperty("user.dir") + "/src/october2018/Q52995381.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("Sheet1");
// Read specific row and column
Row row = sheet.getRow(2);
Cell cell = row.getCell(7);
// This will print data which I want to click
System.out.println(cell);
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/src/drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://www.facebook.com");
if (cell.toString().contentEquals("male")) {
WebElement male_radio_button = driver.findElement(By.xpath("//input[#value='2']"));
male_radio_button.click();
} else {
WebElement female_radio_button = driver.findElement(By.xpath("//input[#value='1']"));
female_radio_button.click();
}

Changing the getROW index in apachee POI throw NullPointerException

I am trying to write to Excel using apachee POI. It works when the getrow index is 0 like[getrow(o)]. But changing it other than zero throw nullpointer exception.
package fairfoxchecking;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class writingInExcel {
public static void main(String []args) throws IOException {
File src = new File("D:/Etl_Bug_reporting_Template.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 =wb.getSheetAt(0);
sheet1.getRow(0).createCell(5).setCellValue("cheasdfasdfasck1");
sheet1.getRow(1).createCell(5).setCellValue("cheasdfasdfasck1");
FileOutputStream fout = new FileOutputStream(src);
wb.write(fout);
wb.close();
}
Before you do create a cell, you have to ensure the row is created.
Try something like,
if(sheet1.getRow(rowIndex) == null)
sheeet1.createRow(rowIndex)
sheet1.getRow(rowIndex).createCell(colIndex).setCellValue(stringVal);
As per this , getRow might return null if it is not defined. So you might have to create one before writing.
sheet1.createRow(index)
Check this lib - seems to be nice.

Issues while writing to Excelsheet using java apache POI

I have two queries as below :-
1) Below is my code to find the total disk space, free and used disk space in my local machine. I want to export these values in a newly created excel sheet under three columns Total Disk Space, Free DiskSpace and UsedDiskSpace.
But in my below code I am able to a create excel sheet under C:\ location but I am not able to set the values of my excel sheet columns to the ones calculated and stored under Total diskspace, FreeDiskSpace and UsedDiskSpace variables. Can anyone suggest me how can I modify my below code to set the excel sheet column values to capacity,Free space and used space variable values etc.
2) How can I convert this code into a .bat executable file so that it can be executed on double click and there is no need to execute the entire code through IDE. Some examples will help!!
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;
import java.io.*;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;
import java.io.File;
import java.util.ArrayList;
public class DiskSpace
{
public static void main(String[] args)
{ try{ String filename="C:/NewExcelFile.xls" ;
HSSFWorkbook workbook=new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FirstSheet");
ArrayList alldisk=null;
alldisk=new ArrayList();
alldisk.add("C:");
File drive=null;
long capacity=0,freespace=0, usedspace=0;
for(int i=0;i<alldisk.size();i++)
{
drive = new File(alldisk.get(i).toString());
capacity = drive.getTotalSpace();
freespace = drive.getFreeSpace();
usedspace = capacity - freespace;
HSSFRow rowhead= sheet.createRow((short)0);
rowhead.getCell(1).setCellValue(capacity);
rowhead.createCell((short) 0).setCellValue(capacity);
rowhead.createCell((short) 1).setCellValue(freespace);
rowhead.createCell((short) 2).setCellValue(usedspace);
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();
}} catch ( Exception ex ) {
System.out.println(ex);
}
}}
Remove
rowhead.getCell(1).setCellValue(capacity);
line.It gives NullPointerException error and don't use createCell(short) it is deprecated method so please remove short type cast.
Here is my code
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;
import java.io.*;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;
import java.io.File;
import java.util.ArrayList;
public class DiskSpace
{
public static void main(String[] args)
{ try{ String filename="/home/likewise-open/EZDI-DOMAIN/cshah/Desktop/NewExamle.xls" ;
HSSFWorkbook workbook=new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FirstSheet");
ArrayList alldisk=null;
alldisk=new ArrayList();
alldisk.add("/home/likewise-open/EZDI-DOMAIN/cshah/Desktop");
File drive=null;
long capacity=0,freespace=0, usedspace=0;
for(int i=0;i<alldisk.size();i++)
{
drive = new File(alldisk.get(i).toString());
capacity = drive.getTotalSpace();
freespace = drive.getFreeSpace();
usedspace = capacity - freespace;
HSSFRow rowhead= sheet.createRow((short)i);
//rowhead.getCell(1).setCellValue(capacity);
rowhead.createCell(0).setCellValue(capacity);
rowhead.createCell(1).setCellValue(freespace);
rowhead.createCell(2).setCellValue(usedspace);
}
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();} catch ( Exception ex ) {
ex.printStackTrace();
}
}}

Categories

Resources