I have one excel file with 4 different sheets to be read for my project. All 4 sheets contain different headers and different number of columns. When I delete all the headers and make everything look same by having same number of columns the code works. But I have no authority to modify the excel sheet as I wish.
Please somebody suggest me a way how to make the excel file to be read with headers even with different number of columns. Here is my code to read excel file:
public class ReadExcelFileAndStore {
public List getTheFileAsObject(String filePath){
List <Employee> employeeList = new ArrayList<>();
try {
FileInputStream file = new FileInputStream(new File(filePath));
// Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
int numberOfSheets = workbook.getNumberOfSheets();
//System.out.println(numberOfSheets);
//loop through each of the sheets
for(int i = 0; i < numberOfSheets; i++) {
// Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(i);
String sheetName = workbook.getSheetName(i);
// Iterate through each rows from first sheet
Iterator <Row> rowIterator = sheet.rowIterator();
Row headerRow= rowIterator.next();
while (rowIterator.hasNext()) {
// Get Each Row
Row row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
Employee employee = new Employee();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
int columnIndex = cell.getColumnIndex();
switch (columnIndex + 1) {
case 1:
employee.setEmpName(cell.getStringCellValue());
break;
case 2:
employee.setExtCode((int) cell.getNumericCellValue());
break;
}
}
employeeList.add(employee);
}
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return employeeList;
}
}
Related
I made poi excel read, upload and save into DB but when I check my DB, excel parsing db without first row. I tried to change code but it doesn't work so I put the my original code. please help!
public static List<Product> excelToExcelEntity(InputStream inputStream) {
try {
Workbook wb = new XSSFWorkbook(inputStream);
Sheet sheet = wb.getSheet(SHEET);
Iterator<Row> rows = sheet.iterator();
List<Product> entities = new ArrayList<Product>();
int rowNumber = 0;
while (rows.hasNext()) {
Row currentRow = rows.next();
if (rowNumber == 0) {
rowNumber++;
continue;
}
Iterator<Cell> cellsInRow = currentRow.iterator();
Product excelEntity = new Product();
DataFormatter formatter = new DataFormatter();
int cellIdx = 0;
while (cellsInRow.hasNext()) {
Cell currentCell = cellsInRow.next();
switch:
---
break;}
cellIdx++;
}
entities.add(excelEntity);
}
wb.close();
return entities;
if (rowNumber == 0) {
rowNumber++;
continue;
}
remove/comment above block code, in here continue will skip further execution and goes back to next element from the list, in your case it's skipping first row.
Please excuse me if I am not clear. English is not my first language.
I'm trying to write a code where I can traverse through the first row of an excel file until I find the column labeled 'Comments'. I want to run some action on the text in that column and then save the result in a new column at the end of the file. Can I traverse the xlsx file in a manner similar to indexes? And if so, how can I jump straight to a cell using that cell's coordinates?
public static void main(String[] args) throws IOException {
File myFile = new File("temp.xlsx");
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
#SuppressWarnings("resource")
XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIterator = mySheet.iterator();
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String comment = cell.toString();
if (comment.equals("Comments"))
{
System.out.println("Hello");
}
}
}
}
For the question "Wanted to go to the second column's 3rd row I could use coordinates like (3, 2)?":
Yes this is possible using CellUtil. Advantages over the methods in Sheet and Row are that CellUtil methods are able getting the cell if it exists already or creating the cell if it not already exists. So existing cells will be respected instead simply new creating them and so overwriting them.
Example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.CellUtil;
import java.util.concurrent.ThreadLocalRandom;
public class CreateExcelCellsByIndex {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
//put content in R3C2:
Cell cell = CellUtil.getCell(CellUtil.getRow(3-1, sheet), 2-1); //-1 because apache poi's row and cell indexes are 0 based
cell.setCellValue("R3C2");
//put content in 10 random cells:
for (int i = 1; i < 11; i++) {
int r = ThreadLocalRandom.current().nextInt(4, 11);
int c = ThreadLocalRandom.current().nextInt(1, 6);
cell = CellUtil.getCell(CellUtil.getRow(r-1, sheet), c-1);
String cellcontent = "";
if (cell.getCellTypeEnum() == CellType.STRING) {
cellcontent = cell.getStringCellValue() + " ";
}
cell.setCellValue(cellcontent + i + ":R"+r+"C"+c);
}
workbook.write(new FileOutputStream("CreateExcelCellsByIndex.xlsx"));
workbook.close();
}
}
FileInputStream file = new FileInputStream(new File(fileLocation));
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
Map<Integer, List<String>> data = new HashMap<>();
int i = 0;
for (Row row : sheet) {
data.put(i, new ArrayList<String>());
for (Cell cell : row) {
switch (cell.getCellTypeEnum()) {
case STRING: ... break;
case NUMERIC: ... break;
case BOOLEAN: ... break;
case FORMULA: ... break;
default: data.get(new Integer(i)).add(" ");
}
}
i++;
}
I'm not sure what you mean by 2D index, but a Cell knows which column it belongs to so something like this should work:
...
Cell cell = cellIterator.next();
String comment = cell.toString();
int sourceColumnIndex = -1;
if (comment.equals("Comments")) {
System.out.println("Hello");
sourceColumnIndex = cell.getColumnIndex();
}
....
Similarly, define something like int targetColumnIndex to represent the column which will have the result from processing all the cells from the sourceColumnIndex column.
Using Apache POI, I am trying to read an excel file. The file has 1000 rows and 1 column. With this code:
XSSFSheet ws = workbook.getSheetAt(0);
Iterator< Row > rowIt = ws.iterator();
XSSFRow row;
int i = 0;
while ( rowIt.hasNext() ) {
row = (XSSFRow) rowIt.next();
Iterator< Cell > cellIt = row.cellIterator();
while ( cellIt.hasNext() ) {
Cell cell = cellIt.next();
my_array[ i ] = cell.getStringCellValue();
}
++i;
}
It seems that it reads 1001 rows and since the last row is "", my_array get invalid string. Is there any way to fix that? I expect rowIt.hasNext() is responsible for that but it doesn't work as expected.
The file has 1000 rows and 1 column : you must specify what column you are reading.
here an exemple that specify column with this excel file:
public class TestLecture {
public static void main(String[] args) throws IOException{
List<String> mys_list= new ArrayList<String>();
FileInputStream file = new FileInputStream(new File("test.xlsx"));
//Get the workbook instance for XLS file
XSSFWorkbook workbook = new XSSFWorkbook (file);
//Get first sheet from the workbook
XSSFSheet ws = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
Iterator<Row> rowIt = ws.iterator();
while (rowIt.hasNext()) {
Row row = rowIt.next();
Iterator<Cell> cellIt = row.iterator();
while (cellIt.hasNext()) {
Cell cell = cellIt.next();
int columnIndex = cell.getColumnIndex();
switch (columnIndex) {
case 2:
mys_list.add(cell.getStringCellValue());
break;
}
}
}
System.out.println(mys_list.size());
for(String g :mys_list){
System.out.println(g);
}
}
}
I want to compare Excel files with each other just to see if they are the same or not. I can choose my Excel Files and Read them. I have 2 Excel Sheets with the same Content but one in .xls and on in .xlsx format.
I use the following Code to read my files (for xls with HSSFWorkbook and so on)
private String xlsx(File inputFile) {
String outputString = "";
// For storing data into String
StringBuffer data = new StringBuffer();
try {
// Get the workbook object for XLSX file
XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(inputFile));
// Get first sheet from the workbook
XSSFSheet sheet = wBook.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();
data.append(cell + ";");
}
data.append("\n");
}
System.out.println(data.toString());
outputString = data.toString();
wBook.close();
} catch (Exception ioe) {
ioe.printStackTrace();
}
return outputString;
}
In my Excel I have blank cells - when i read them with xls I get DATA;;;;;DATA which is correct but When i Do the same in xlsx I get DATA;DATA
Somehow the Code skips empty cells?! How can I fix this Problem?
Thanks in Advance
After some more Google research and trying different things i found a solution to my Problem. The Iterator skips empty Cells because they have no value - they are null - however in a xls File it seems like they are not null - Whatever
My Code:
private String xlsx(File inputFile) {
String outputString = "";
System.out.println("start");
// For storing data into String
StringBuffer data = new StringBuffer();
try {
// Get the workbook object for XLSX file
XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(inputFile));
// Get first sheet from the workbook
XSSFSheet sheet = wBook.getSheetAt(0);
// Decide which rows to process
int rowStart = 0;
int rowEnd = sheet.getLastRowNum()+1;
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
Row r = sheet.getRow(rowNum);
int lastColumn = r.getLastCellNum();
for (int cn = 0; cn < lastColumn; cn++) {
Cell c = r.getCell(cn);
if (c == null) {
data.append("" + ";");
} else {
data.append(c + ";");
}
}
data.append("\n");
}
System.out.println(data.toString());
outputString = data.toString();
wBook.close();
} catch (Exception ioe) {
ioe.printStackTrace();
}
System.out.println("end");
return outputString;
}
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..