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());
Related
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.
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 "";
}
}
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?
I have an Excel sheet I need to print the adjacent cell value when I am seeing the empty cell in java.
I had written the code to print the values in the Excel sheet and I too find the empty cell but I don't how to print the adjacent cell value on seeing the empty cell
public class empty {
public static void main(String args[]) throws Exception {
InputStream ExcelFileToRead = new FileInputStream("C:\\Users\\GOMATHI\\Desktop\\data1.xls");
HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext()) {
cell = (HSSFCell) cells.next();
if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
// logic goes here. I don't know.
System.out.println(no);
}
System.out.println(cell.toString());
}
}
// System.out.println();
}
}
Input: Excel File
Id Value
01 200
02 201
03 203
04
05 205
Output:
The Value at 4th cell Value is empty so I need to print its corresponding ID.
04
First, I think your test if (cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) is half useless because cell should never be null.
Assuming this, you can get the cell of the previous column with row.getCell(cell.getColumnIndex() - 1)
I'm reading Excel file using Apache POI.
My Excel table structure is like this
|2000s| 2001, 2003, 2008, 2009|
so for right hand side data, I require it to assign to 2000s
Till now I've implemented this way:
List<Class> list = new ArrayList<Class>();
File file = new File(file_path);
FileInputStream fis = new FileInputStream(file);
//Create an instance of workbook which refers to an excel file
XSSFWorkbook wb = new XSSFWorkbook(fis);
//This selects the 1st sheet
XSSFSheet sheet = wb.getSheetAt(0);
//Iterate through each row one by one
Iterator<Row> itr = sheet.iterator();
String newName = null;
String oldName = null;
while(itr.hasNext()){
Row nextRow = itr.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
newName = nextRow.getCell(0).toString();
if(nextRow.getCell(1).toString().contains(",")){
StringTokenizer st = new StringTokenizer(nextRow.getCell(1).toString(),",");
while(st.hasMoreTokens()){
oldName = st.nextToken();
}
}
else{
oldName = nextRow.getCell(1).toString();
}
}
System.out.println();
}
When I compile, it throws me "Null pointer Exception" at nextRow.getCell(1) line.
I don't understand how do I map all comma values to 2000s.
This is working perfectly fine for normal data(without comma).
Comma values have been handled
I'm posting answer so somebody can get help from here.
What I've done is- added String Tokenizer class and if there's comma in the cell, it breaks the value with the comma delimiter.
Lets have a look at the code below
while(itr.hasNext()){
Row nextRow = itr.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
newName = nextRow.getCell(0).toString();
if(nextRow.getCell(1).toString().contains(",")){
StringTokenizer st = new StringTokenizer(nextRow.getCell(1).toString(),",");
while(st.hasMoreTokens()){
oldName = st.nextToken();
}
}
else{
oldName = nextRow.getCell(1).toString();
}
}
System.out.println();
}
Here newName gets the value of 1st col.(2000s)
and oldName gets the tokens based on ',' delimiter- In this case 2001, 2003, 2008, 2009
for all these values of oldName, newName 2000s would be mapped.
UPDATE: Reason I was getting 'Null Pointer Exception' there, because some cells at 2nd column(nextRow.getCell(1)) are null.
So whenever iterator reaches to the null cell, it throws Null Pointer Exception.
Here you need to assign Missing Cell Policy
by
Cell cell2 = row.getCell(j,org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK);
(It just treats null values as blank)
This way you can also resolve Null pointer exception in Excel while reading from Null values