Reading excel cells containing alphanumeric data in Java - java

I am trying to get the values from cells in an excel spreadsheet that contain both letters and numbers. Below is a sample of my code:
String excelFilePath = "FILEPATH";
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = firstSheet.iterator();
iterator.next();
while (rowIterator.hasNext()) {
Row nextRow = rowIterator.next();
Iterator<Cell> cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext()) {
Cell nextCell = cellIterator.next();
int columnIndex = nextCell.getColumnIndex();
switch (columnIndex) {
case 0:
String name = nextCell.getStringCellValue();
break;
case 1:
Date enrollDate = nextCell.getDateCellValue();
case 2:
String userid = nextCell.getStringCellValue();
}
}
My question is in relation to case 2.User IDs can either be letters, numbers or a mix of both for example: (AX77552, 112321, ASWTT)If I say getStringCellValue() I get an error and I also get an error if I say getNumericCellValue(). Is there any way that I can make it so that you can get numeric and string values for the cells in this row of data?

Related

cellIterator.hasNext() returns false even the cell has value

I use the following approach to read data from excel (csv) sheet:
InputStream inputStream = new BufferedInputStream(multipartFile.getInputStream());
XSSFWorkbook myWorkBook = new XSSFWorkbook(inputStream);
List<String> cellList = new ArrayList<>();
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIterator = mySheet.iterator();
rowIterator.next();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
cellList.clear();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) { // this returns false even the cell has data
Cell cell = cellIterator.next();
cellList.add(cell.getStringCellValue());
}
}
I want to make cellIterator.hasNext() returns true for empty cell values as in the second row (name). So, how can I do that?
Create Date Uuid Name
2021-09-29 2e81a2b6-3226-4fe0-b8bd-39f42239686d admin
2021-09-30 610e9040-840c-48c5-aa64-f193ed896133
You can't make cellIterator.hasNext() return true for the empty "name" cell.
If you know in advance the number of column in advance, you can use a loop and row.getCell(index).
for (int i = 0; i < 3; i++) {
Cell cell = row.getCell(i);
cellList.add(cell == null ? "Empty":cell.toString());
}
If you don't, you have to scan first of your file to count the number of columns.

Java: How to push the excel data in to java map(<string,ArrayList<Strings>)

I am facing a weird problem here, i need to read the excel data which starts after some rows.
My excel input is something like below
Row1 : This report is to display all the user details
Row2 : Kindly find the below details
Row3 : TABLE1 (This is the identifier after this row my table data is available).
Row4 : ID Name DOB
Row5 : 101 RAM 10-07-1986
Row6 : 102 Sita 24-08-1989
Row6 : Table2
note:i need to read only row4 to row6jav
I need the output like below in the map,
mymap [ID =[101,102],[Name = RAM,Sita],[DOB = 10-07-1986,24-08-1989]]
I have tried the below code which is working absolutely fine if my first 3 rows are not there, only creating issue if i give first 3 rows. your help is much appreciated.
public static void main(String[] args) {
try {
File file = new File("C:\\demo\\employee.xlsx"); //creating a new file instance
FileInputStream fis = new FileInputStream(file); //obtaining bytes from the file
//creating Workbook instance that refers to .xlsx file
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0); //creating a Sheet object to retrieve object
Iterator<Row> itr = sheet.iterator(); //iterating over excel file
// CAREFUL HERE! use LinkedHashMap to guarantee the insertion order!
Map<String, List<String>> myMap = new LinkedHashMap<>();
// populate map with headers and empty list
if (itr.hasNext()) {
Row row = itr.next();
Iterator<Cell> headerIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
myMap.put(getCellValue(cell), new ArrayList<>());
}
}
Iterator<List<String>> columnsIterator;
// populate lists
while (itr.hasNext()) {
// get the list iterator every row to start from first list
columnsIterator = myMap.values().iterator();
Row row = itr.next();
Iterator<Cell> cellIterator = row.cellIterator(); //iterating over each column
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// here don't check hasNext() because if the file not contains problems
// the # of columns is same as # of headers
columnsIterator.next().add(getCellValue(cell));
}
}
// here your map should be filled with data as expected
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getCellValue(Cell cell) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING: //field that represents string cell type
return cell.getStringCellValue() + "\t\t\t";
case Cell.CELL_TYPE_NUMERIC: //field that represents number cell type
return cell.getNumericCellValue() + "\t\t\t";
case Cell.CELL_TYPE_Date: //field that represents Date cell type
return cell.getDateCellValue() + "\t\t\t";
default:
return "";
}
}

How to read drop list items in excel cell value?

I have saved contact details of the same type in the same cell(e.g person has more than one email address) I have saved them as a list in one cell but I'm not able to read them when iterating through my excel sheet. I can only read the currently selected/displayed, other options are ignored. I'm using java
//Read sheet inside the workbook by its name
Sheet _workSheet = _workbook.getSheet(sheetName);
//Iterate through each rows
Iterator<Row> rowIterator = _workSheet.iterator();
while(rowIterator.hasNext())
{
//Get Each Row
Row row_ = rowIterator.next();
//Iterator through each column of each row
Iterator<Cell> cellIterator = row_.cellIterator();
while(cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Checking the cell format
switch(cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue()+"\n");
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue()+"\n");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue()+"\n");
break;
case Cell.CELL_TYPE_BLANK:
System.err.println(cell.getStringCellValue()+" .....empty cell");
break;
}
}
System.err.println("");
}
In cell "A2" I'm expecting to get two values (emailone, emailTwo)
These did the trick;
List<XSSFDataValidation> dataValidations = sheet.getDataValidations();
Iterator<XSSFDataValidation> iterator = dataValidations.iterator();
XSSFDataValidation dataValidation = iterator.next();
String[] explicitListValues = dataValidation.getValidationConstraint().getExplicitListValues();

Append Excel columns with XSSFWorkbook

I have an excel sheet, and I want to selectively transfer its content to a list. The object has 2 attributes, String id, String str.
I want to set the first column as id. I got this part right. I also want to append the values of column 3,4,6,7. For example, if my excel looks like:
4404A01459C1 || A1 || 13 || 14 || B1 || 8 || 7
I want 4404A01459C1 as id(again, I got this part). Then I want 13;14;8;7, skipping A1 and B1, separating the values with ; How do I achieve this?
FileInputStream inputStream = new FileInputStream("D:\\work\\calculatepi\\test.xlsx");
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = firstSheet.iterator();
List<SampleGene> sgl=new ArrayList<SampleGene>();
while(rowIterator.hasNext()){
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
SampleGene sg = new SampleGene();
sg.setId(row.getCell(0).toString());
//need help here
sgl.add(sg);
}
return null;
Try using StringBuilder and iterate over cellIterator;append each cell value to the StringBuilder.
StringBuilder sb = new StringBuilder();
while(cellIterator.hasNext())
{
sb.append(cellIterator.next().toString());
sb.append(";");
}
sg.setStr(sb.toString());

How to read excel file data each cell and save that data into database table as per the column name

I am trying to read excel file data and saving that data into the database.
data is comming to console. I have two column in excel file namely Userid and RequestId I am trying to save the data similarly in the database table in the same manner.
Data is going in the table but both columns are having same value.
I need them seperately.I am using this code for reading.
FileInputStream file2 = new FileInputStream(new File("C://excel.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file2);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
rowIterator.next();
while(rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext())
{
Cell cell = cellIterator.next();
double value2=(int) cell.getNumericCellValue();
System.out.println("value1: "+value2);
}`
In console it is showing correctly but the data is not going in that manner in database
Please help me
Thanks in advance
With some Data class:
class Data {
private final double val1;
private final double val2;
public Data(final double val1; final double val2) {
this.val1 = val1;
this.val2 = val2;
}
// getters etc
}
and
final List<Data> datas = new ArrayList<>();
for (final Row r : sheet) {
// Maybe skip an header row
final Cell cell1 = r.getCell(0); // 0-based
final Cell cell2 = r.getCell(1);
if (cell1 != null && cell2 != null) {
datas.add(new Data(cell1.getNumericCellValue(), cell2.getNumericCellValue()));
}
}
// TODO: write datas to DB
NB: wild code (i.e. didn't even try to compile it)
Some reading: https://poi.apache.org/spreadsheet/quick-guide.html#Iterator

Categories