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() + ",");
Related
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;
}
}
I am trying to read excel file cell by cell.The problem i am facing is ,my program skip one cell value while reading the excel file. Below is the code.
private void ReadExcel {
try
{
FileInputStream file = new FileInputStream(new File("C:\\Users\\Desktop\\abc.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Create a blank sheet
XSSFSheet spreadsheet = workbook.getSheetAt(0);
//Create row object
HashMap<Integer,List> hm = new HashMap<Integer,List>();
Integer index = 0;
//This data needs to be written (Object[])
Iterator<Row> rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext())
{
List cellDataList = new ArrayList();
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
//System.out.println(cell.getDateCellValue());
cellDataList.add(cell.getDateCellValue());
} else {
//System.out.println(cell.getNumericCellValue());
cellDataList.add(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_STRING:
//System.out.print(cell.getStringCellValue() + "\t");
cellDataList.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
//System.out.println(cell.getStringCellValue() + "\t");
cellDataList.add(cell.getStringCellValue());
}
}
hm.put(index, cellDataList);
System.out.println("Size of hashmap is " +hm.size());
List al =hm.get(index);
System.out.println("List Size is " +al.size());
for(int i = 0;i<al.size();i++)
{
//System.out.println(" " +al.get(i));
}
System.out.println();
index++;
System.out.println("");
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Exception " +e);
}
}
Input data file i am passing to method is
I shared the input file screen shot. The problem i am facing is , i am able to read all cell value of first row and get the size of 4 but when i read second row , value of coloumn "D" is getting skip and getting size of 3. I dont why its skip the second row "D" Coloumn.
use normal for instead
do something like this
Row oRow = sheet.createRow(rowCounter);
for (short cell = 0; cell < row.getLastCellNum(); cell++) {
System.out.println("Reading Cell number: "+cell);
Cell cell0 = oRow.createCell(cell);
cell0.setCellValue(row.getCell(cell).toString());
}
I have a Excel file in .xlsx format. I have stored data by merging cells to form various columns. I am reading the Excel file via a Java web application and saving its data to a database (MySQL). But when I read from merged cells I get null values along with what are stored in the columns as well as the headers. I am using Apache POI. My code is:
public static void excelToDBLogIN() {
FileInputStream file = null;
Boolean flag = true;
ArrayList<String> rows = new ArrayList<String>();
try {
// here uploadFolder contains the path to the Login 3.xlsx file
file = new FileInputStream(new File(uploadFolder + "Login 3.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();
String tuple = "";
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
//int value = new BigDecimal(cell.getNumericCellValue()).setScale(0, RoundingMode.HALF_UP).intValue();
//tuple = tuple + String.valueOf(value) + "+";
DataFormatter objDefaultFormat = new DataFormatter();
String str = objDefaultFormat.formatCellValue(cell);
tuple = tuple + str + "+";
break;
case Cell.CELL_TYPE_STRING:
tuple = tuple + cell.getStringCellValue() + "+";
break;
case Cell.CELL_TYPE_BLANK:
tuple = tuple + "" + "+";
break;
}
}
rows.add(tuple);
flag = true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
file = null;
} catch (Exception e) {
System.out.println("File closing operation failed");
e.printStackTrace();
}
}
}
}
}
I searched for answers in the web but did not find anything relevant.
Following code of snippet might help.
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
outer:
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
//will iterate over the Merged cells
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress region = sheet.getMergedRegion(i); //Region of merged cells
int colIndex = region.getFirstColumn(); //number of columns merged
int rowNum = region.getFirstRow(); //number of rows merged
//check first cell of the region
if (rowNum == cell.getRowIndex() && colIndex == cell.getColumnIndex()) {
System.out.println(sheet.getRow(rowNum).getCell(colIndex).getStringCellValue());
continue outer;
}
}
//the data in merge cells is always present on the first cell. All other cells(in merged region) are considered blank
if (cell.getCellType() == Cell.CELL_TYPE_BLANK || cell == null) {
continue;
}
System.out.println(cell.getStringCellValue());
}
}
This method can read a specific cell (including merged cell):
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public static void readCell(String excelFilePath, int rowIndex, int columnIndex) throws FileNotFoundException, IOException {
try (InputStream inp = new FileInputStream(excelFilePath)) {
XSSFWorkbook wb = new XSSFWorkbook(inp);
XSSFCell cell = wb.getSheetAt(0).getRow(rowIndex).getCell(columnIndex);
switch (cell.getCellType()) {
case STRING:
System.out.println(cell.getRichStringCellValue().getString());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
System.out.println(cell.getDateCellValue());
} else {
System.out.println(cell.getNumericCellValue());
}
break;
case BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case FORMULA:
System.out.println(cell.getCellFormula());
break;
case BLANK:
System.out.println();
break;
default:
System.out.println();
}
wb.close();
}
}
Dependencies: POI 5.0.0, JDK 1.8.0
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..
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();