Convert XSSFSheet to List<Pojo> with poi apache in Java - java

Is there any way we can covert the XSSFSheet to the list of POJO.
The number of rows will result in the size of ArrayList.
Here is the below sheet I have.
And here is the POJO -
public class Sprint {
String name;
Integer age;
String phone;
// getter and setters
}
And here is function -
public String singleFileUpload(FileBucket fileBucket) throws IOException {
MultipartFile multipartFile = fileBucket.getFile();
FileCopyUtils.copy(fileBucket.getFile().getBytes(), new File(UPLOAD_LOCATION + fileBucket.getFile().getOriginalFilename()));
XSSFWorkbook workbook = new XSSFWorkbook(multipartFile.getInputStream());
XSSFSheet sheet = workbook.getSheetAt(0);
List<Sprint> sprint= new ArrayList();
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
// here I want to convert sheet to list of POJO
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "t");
break;
}
}
}
return "success";
}
Please help!.
Thanks in advance.

Related

How to read contents of Excel sheet and storing it in a map with column1 as key, and the remaining columns as values

I have an excel sheet which looks like this :
Col_1 | Col_2| Col_3 | Col_4
A | B | C | D
A1 | B1 | C1 | D1
How to read this excel and store the values in a map with A as key, and B,C,D as values for that key.
Please find my codes below, which is not working as expected.
while (rowIterator.hasNext())
{
ArrayList<String> columnlist = new ArrayList<String>();
List excelValues = new ArrayList();
String key = StringUtils.EMPTY;
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
if(row.getRowNum() > 0)
{
if(cell.getColumnIndex()==0){
key = StringUtils.upperCase(cell.getStringCellValue());
}
else if(cell.getColumnIndex()==1)
{
tempPar = cell.getStringCellValue();
excelValues.add(tempPar);
}
if(tempPar.equalsIgnoreCase("Include")){
if(cell.getColumnIndex()==2)
{
// Responsible for reading comma separated values from cell in excel sheet.
StringTokenizer str= new StringTokenizer(cell.getStringCellValue(),COMMA);
while (str.hasMoreElements()) {
columnlist.add(StringUtils.upperCase(str.nextElement().toString()));
}
excelValues.add(columnlist.equals("") ? "" : columnlist);
}
else if(cell.getColumnIndex()==3){
ignorePK = cell.getStringCellValue();
ignorePK.add(cell.getStringCellValue());
excelValues.add(ignorePK);
}
}
map.put(key, excelValues);
}
I have written the code to read excel and store it to database using Apache Poi . You can refer it out and modify your own code.
try {
ExcelController ex = new ExcelController();
File f1 = ex.convert(file);
// FileInputStream file = new FileInputStream(new File("E://Imp/Details.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(f1);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
rowIterator.next();
// while (rowIterator.hasNext()) {
for(int i=1;i<=51;i++){
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// System.out.println("cell.getStringCellValue().length() "+cell.getStringCellValue().length());
// if( cell.getStringCellValue().length()>0){
List list = new ArrayList();
// This will change all Cell Types to String
cell.setCellType(Cell.CELL_TYPE_STRING);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
String bstring = "" + cell.getBooleanCellValue();
list.add(cell.getBooleanCellValue());
System.out.println("boolean===>>>" + cell.getBooleanCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
String Nstring = "" + cell.getNumericCellValue();
list.add(Nstring);
break;
case Cell.CELL_TYPE_STRING:
list.add(cell.getStringCellValue());
break;
}
// }else {
// break;
// }
}
After you get the values over there just push it to the Map you have created.

How do i write list data to existing xlsx file in particular column without overwriting using java

I have two 'xlsx' files 'sss.xlsx' and 'abc.xlsx'.
In 'sss.xlsx' file there are some Headers (columns only, doesn't contain any data) and in 'abc.xlsx' file there is data.
I wants to copy data from 'abc' file to 'sss' file column by column by checking column names. If column name matches then copy that column data to "sss.xlsx"
In same column (keep column as it is given in sss file).
I tried with below code. I am able to write but while writing header gets deleted. I am not getting where I went wrong.
Code:
public class Read {
private static int flag;
public static void main(String[] args) throws IOException{
//Create blank workbook
HSSFWorkbook workbook1 = new HSSFWorkbook();
//Create a blank sheet
HSSFSheet spreadsheet = workbook1.createSheet(
" Info ");
ArrayList<String> lst = new ArrayList<String>();
Read read = new Read();
File f2 = new File("sss.xlsx");
FileInputStream ios2 = new FileInputStream(f2);
XSSFWorkbook workbook2 = new XSSFWorkbook(ios2);
XSSFSheet sheet2 = workbook2.getSheetAt(0);
int noOfColumns = sheet2.getRow(0).getLastCellNum();
System.out.println(noOfColumns);
//String temp2=f.getSheet();
Iterator<Row> rowIterator = sheet2.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator <Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell1 = cellIterator.next();
String temp2=cell1.getStringCellValue().toString();
System.out.print(cell1.getStringCellValue() + "\n");
lst = read.extractExcelContentByColumnIndex(temp2);
File f3 = new File("sss.xlsx");
FileInputStream ios = new FileInputStream(f3);
XSSFWorkbook workbook3 = new XSSFWorkbook(ios);
String temp1=f3.getName();
//String colName="Mob No";
XSSFSheet sheet3 = workbook3.getSheetAt(0);
//String temp2=f.getSheet();
int columnIndex1=0;
Iterator<Row> rowIterator3 = sheet3.iterator();
//columndata = new ArrayList<String>();
while (rowIterator3.hasNext()) {
Row row3 = rowIterator3.next();
Iterator<Cell> cellIterator3 = row3.cellIterator();
while (cellIterator3.hasNext()) {
Cell cell3 = cellIterator3.next();
String temp5=cell3.getStringCellValue().toString();
//System.out.println(temp);
if(temp5.equals(temp2)){
columnIndex1 = cell1.getColumnIndex();
System.out.println(columnIndex1);
flag=1;
break;
}
}
if(flag==1)
{
flag = 0;
break;
}
}
while (rowIterator.hasNext()) {
Row row6 = rowIterator.next();
// System.out.println(row.getRowNum());
Iterator<Cell> cellIterator6 = row6.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(row.getRowNum() > 0){ //To filter column headings
if(cell.getColumnIndex() == columnIndex1){// To match column index
// }
}
}
}
}
for(int RowNum=0; RowNum<lst.size();RowNum++){
HSSFRow row1 = spreadsheet.createRow(RowNum+1);
HSSFCell cell6 = row1.createCell(columnIndex1);
cell6.setCellValue(lst.get(RowNum).toString());
}
}
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("sss.xlsx"));
// System.out.println(lst);
workbook1.write(out);
out.close();
}
}
public ArrayList<String> extractExcelContentByColumnIndex( String colName)
{
ArrayList<String> columndata = null;
int columnIndex= 0;
int flag=0;
try {
File f = new File("abc.xlsx");
FileInputStream ios = new FileInputStream(f);
XSSFWorkbook workbook = new XSSFWorkbook(ios);
String temp1=f.getName();
XSSFSheet sheet = workbook.getSheetAt(0);
//String temp2=f.getSheet();
Iterator<Row> rowIterator = sheet.iterator();
columndata = new ArrayList<String>();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell1 = cellIterator.next();
String temp=cell1.getStringCellValue().toString();
//System.out.println(temp);
if(temp.equals(colName)){
columnIndex=cell1.getColumnIndex();
flag=1;
break;
}
}
if(flag==1)
{
flag = 0;
break;
}
}
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// System.out.println(row.getRowNum());
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(row.getRowNum() > -1){ //To filter column headings
if(cell.getColumnIndex() == columnIndex){// To match column index
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
columndata.add(cell.getNumericCellValue()+"");
break;
case Cell.CELL_TYPE_STRING:
columndata.add(cell.getStringCellValue());
break;
}
}
}
}
}
ios.close();
System.out.println(colName);
for(String ele : columndata)
{
System.out.println(ele);
}
} catch (Exception e) {
e.printStackTrace();
}
return columndata;
}
}
Thanks in advance!

How to get the excel sheet each row and column value

I have the excel file the code works fine, but how can I get each column and row value differently so that I can store the value in database. Thank you in advance
public class excel_demo {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:\\Users\\Admin\\Downloads\\ExcelDemosWithPOI\\howtodoinjava_demo.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
download JEXCEL api,and use this code,
import jxl.*;//import jxl package.
File excelSheet = null;
Workbook workbook = null;
Workbook wb = Workbook.getWorkbook(new File(destFile));//destFile is excel file
Sheet sheet = wb.getSheet(sheetNo);
columns = sheet.getColumns();
rows = sheet.getRows();
for(int row = 0;row <rows;row++)
{
for(int col =0;col <columns;col++)
{
a[row][col] =Integer.parseInt( sheet.getCell(col,row).getContents());
}
}
Hope this helps..

How to get value from excel using apache poi

I just tried to get each cell values from excel file but i get each cell already merged but i want each cell different
import java.io.File;import java.io.FileInputStream;import java.util.Iterator;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;public class Read {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
FileInputStream file = new FileInputStream(new File("D://new/excelnew/student_usr_mst_dtls.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue());
break;
}
}
System.out.println("");
}
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
and OutPut is like as string
IDNAMELASTNAME
1.0tAmitShukla
2.0tLokeshGupta
I want each cell uniquely so how to do it. if possible give an example please.
Put a comma after each cell value you print.
System.out.print(cell.getNumericCellValue() + "t,");
and
System.out.print(cell.getStringCellValue() + ",");

Convert .xls to .csv in Java

I want to convert the xls file to csv. I successfully converted it to a csv file, but the last column also has a comma appended. How do I remove the last comma, example 1,2,2,3,... Could you please help out?
package bwtest;
import java.io.*;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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;
class ExcelToCSV {
static void convertToXlsx(File inputFile, File outputFile) {
// For storing data into CSV files
StringBuffer cellValue = new StringBuffer();
try {
FileOutputStream fos = new FileOutputStream(outputFile);
// Get the workbook instance for XLSX file
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(inputFile));
// Get first sheet from the workbook
XSSFSheet sheet = wb.getSheetAt(0);
Row row;
Cell cell;
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
cellValue.append(cell.getBooleanCellValue() + ",");
break;
case Cell.CELL_TYPE_NUMERIC:
cellValue.append(cell.getNumericCellValue()
+ ",");
break;
case Cell.CELL_TYPE_STRING:
cellValue.append(cell.getStringCellValue() + ",");
break;
case Cell.CELL_TYPE_BLANK:
cellValue.append("" + ",");
break;
default:
cellValue.append(cell + ",");
}
}
}
fos.write(cellValue.toString().getBytes());
fos.close();
} catch (Exception e) {
System.err.println("Exception :" + e.getMessage());
}
}
static void convertToXls(File inputFile, File outputFile) {
// For storing data into CSV files
StringBuffer cellDData = new StringBuffer();
try {
FileOutputStream fos = new FileOutputStream(outputFile);
// Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(
inputFile));
// Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell;
Row row;
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
cellDData.append(cell.getBooleanCellValue() + ",");
break;
case Cell.CELL_TYPE_NUMERIC:
cellDData.append(cell.getNumericCellValue() + ",");
break;
case Cell.CELL_TYPE_STRING:
cellDData.append(cell.getStringCellValue() + ",");
break;
case Cell.CELL_TYPE_BLANK:
cellDData.append("" + ",");
break;
default:
cellDData.append(cell + ",");
}
}
}
fos.write(cellDData.toString().getBytes());
fos.close();
} catch (FileNotFoundException e) {
System.err.println("Exception" + e.getMessage());
} catch (IOException e) {
System.err.println("Exception" + e.getMessage());
}
}
public static void main(String[] args)
{
File inputFile = new File("C:\input.xls");
File outputFile = new File("C:\output1.csv");
File inputFile2 = new File("C:\input.xlsx");
File outputFile2 = new File("C:\output2.csv");
convertToXls(inputFile, outputFile);
convertToXlsx(inputFile2, outputFile2);
}
}
Assuming every row has cells:
After your cellIterator loop and before you rowIterator loop finishes, add:
cellDData.deleteCharAt(cellDData.length()-1);
This should delete the last comma in the line.
If it's possible to have a row where the cellIterator doesn't run(which I doubt) then you can put boolean hasCells = false; before the cellIterator loop, and set hasCells = true; inside of the loop somewhere. Then, only delete the comma if(hasCells)
Your conversion algorithm is incorrect.
Instead of adding value then comma,
you should add comma (if needed) then value.
Here is some code:
...
int columnNumber = 1;
while (cellIterator.hasNext())
{
if (columnNumber > 1)
{
cellValue.append(",")
}
row = rowIterator.next();
switch (cell.getCellType())
{
... append the cell value to the cellValue.
}
++columnNumber;
}
...
After each row you will need to insert a line feed "/r/n" and remove the last coma.
You can write it to the fos at that time.
if (cellDData != null && cellDData.length() > 1) {
String cellDDataString = cellDData.toString();
cellDDataString = cellDDataString.substring(0,cellDDataString.length() - 1) + "/r/n";
fos.write(cellDDataString);
}
cellDData = new StringBuffer();

Categories

Resources