Hi there i was following a tutorial regarding the data driven testing in selenium and i want to read data from the excel file .xlsx but its giving me null pointer.
Below is the code:
package com.usman;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class ReadDataFromExcelSheet {
public String[][] getExcelData(String excellocation, String sheetName) {
try {
String dataSets[][] = null;
FileInputStream file = new FileInputStream(new File(excellocation));
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheet(sheetName);
// count number of active rows
int totalRow = sheet.getLastRowNum();
// count number of active columns in row
int totalColumn = sheet.getRow(0).getLastCellNum();
// Create array of rows and column
dataSets = new String[totalRow][totalColumn];
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
int i = 0;
while (rowIterator.hasNext()) {
System.out.println(i);
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
int j = 0;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell.getStringCellValue().contains("User Name")) {
break;
}
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
dataSets[i - 1][j++] = cell.getStringCellValue();
System.out.println(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
dataSets[i - 1][j++] = cell.getStringCellValue();
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
dataSets[i - 1][j++] = cell.getStringCellValue();
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
dataSets[i - 1][j++] = cell.getStringCellValue();
System.out.println(cell.getStringCellValue());
break;
}
}
System.out.println("");
i++;
}
file.close();
return dataSets;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void updateResult(String excellocation, String sheetName, String testCaseName, String testStatus) throws IOException {
try {
FileInputStream file = new FileInputStream(new File(excellocation));
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheet(sheetName);
// count number of active tows
int totalRow = sheet.getLastRowNum() + 1;
// count number of active columns in row
for (int i = 1; i < totalRow; i++) {
XSSFRow r = sheet.getRow(i);
String ce = r.getCell(1).getStringCellValue();
if (ce.contains(testCaseName)) {
r.createCell(2).setCellValue(testStatus);
file.close();
System.out.println("resule updated");
FileOutputStream outFile = new FileOutputStream(new File(excellocation));
workbook.write(outFile);
outFile.close();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Object[][] getExcelDataBasedOnStartingPoint(String excellocation, String sheetName, String testName) {
try {
String dataSets[][] = null;
FileInputStream file = new FileInputStream(new File(excellocation));
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheet(sheetName);
// count number of active rows
int totalRow = sheet.getLastRowNum();
int totalColumn = 0;
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
int i = 0;
int count = 1;
while (rowIterator.hasNext() && count == 1 || count == 2) {
// System.out.println(i);
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
int j = 0;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell.getStringCellValue().contains(testName + "end")) {
count = 0;
break;
}
// System.out.println(sheetName+"Start");
if (cell.getStringCellValue().contains(testName + "start")) {
// count number of active columns in row
totalColumn = row.getPhysicalNumberOfCells() - 1;
// Create array of rows and column
dataSets = new String[totalRow][totalColumn];
}
// System.out.println(sheetName+"Start");
if (cell.getStringCellValue().contains(testName + "start") || count == 2) {
System.out.println(sheetName + "start");
count = 2;
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
dataSets[i - 1][j++] = cell.getStringCellValue();
System.out.println(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
if (!cell.getStringCellValue().contains(testName + "start")) {
dataSets[i - 1][j++] = cell.getStringCellValue();
System.out.println(cell.getStringCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
dataSets[i - 1][j++] = cell.getStringCellValue();
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
dataSets[i - 1][j++] = cell.getStringCellValue();
System.out.println(cell.getStringCellValue());
break;
}
}
}
System.out.println("");
i++;
}
file.close();
return parseData(dataSets, totalColumn);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* This method is used to remove unwanted null data from array
*
* #param data
* #return
*/
public Object[][] parseData(Object[][] data, int colSize) {
// Creating array list to store data;
ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
// This array list will store one Array index data, every array index
// has three sets of data
ArrayList<String> list1;
System.out.println(data.length);
// running for loop on array size
for (int i = 0; i < data.length; i++) {
// creates a list to store the elements != null
System.out.println(data[i].length);
list1 = new ArrayList<String>();
// this for loop will run on array index, since each array index has
// three sets of data
for (int j = 0; j < data[i].length; j++) {
// this if will check null
if (data[i][j] != null) {
list1.add((String) data[i][j]);
}
}
// once all one array index data is entered in arrayList , then
// putting this object in parent arrayList
if (list1.size() > 0) {
list.add(list1);
}
}
// convert array List Data into 2D Array
Object[][] arr2d = new Object[list.size()][colSize];
// run loop on array list data
for (int i = 0; i < list.size(); i++) {
// every array list index has arryList inside
ArrayList<String> t = list.get(i);
// run loop on inner array List
for (int j = 0; j < t.size(); j++) {
arr2d[i][j] = t.get(j);
}
}
System.out.println(list);
System.out.println(arr2d);
return arr2d;
}
public static void main(String[] args) throws IOException {
String excellocation = "D:\\usman data\\excel-tutorial-with-dataDrivenFramework-master\\excel-tutorial-with-dataDrivenFramework-master\\src\\main\\resources\\testData\\demo.xlsx";
String sheetName = "login";
ReadDataFromExcelSheet excel = new ReadDataFromExcelSheet();
Object[][] data = excel.getExcelDataBasedOnStartingPoint(excellocation, sheetName, "login");
System.out.println(data);
// excel.updateResult(excellocation, sheetName, "Login Test", "FAIL");
// excel.updateResult(excellocation, sheetName, "Registartion Test",
// "PASS");
// excel.updateResult(excellocation, sheetName, "Dashboard Test",
// "PASS");
}
}
I am getting the following error:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.dom4j.io.SAXContentHandler (file:/C:/Users/True%20Meridian/.m2/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar) to method com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser$LocatorProxy.getEncoding()
WARNING: Please consider reporting this to the maintainers of org.dom4j.io.SAXContentHandler
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
java.lang.NullPointerException
null
at com.usman.ReadDataFromExcelSheet.getExcelDataBasedOnStartingPoint(ReadDataFromExcelSheet.java:130)
at com.usman.ReadDataFromExcelSheet.main(ReadDataFromExcelSheet.java:258)
On XSSFSheet sheet = workbook.getSheet(sheetName); in method getExcelDataBasedOnStartingPoint it probably returns null. If it does, the name provided is not the sheet name of any sheet in the workbook. You should check for null. Like this:
XSSFSheet sheet = workbook.getSheet(sheetName);
if (sheet == null) throw new IllegalArgumentException("Sheet with sheet name " + sheetName + " does not exist");
This being said, this does not exactly resolve your issue. Your main issue is, that sheet "login" does not exist in the workbook "D:\usman data\excel-tutorial-with-dataDrivenFramework-master\excel-tutorial-with-dataDrivenFramework-master\src\main\resources\testData\demo.xlsx".
Related
I am having 100 excel files and I want to merge all of them into one excel file. Here in my example I am having 2 excel files and I want to merge them into one. I can't do it. I am using Apache POI API.
In one excel workbook there can be more than one sheets also so I want to iterate through sheets of each workbook also.
I tried and researched but I got this link and it's not working for me
https://dev.to/eiceblue/merge-excel-files-in-java-2lo2#:~:text=A%20quick%20way%20to%20merge,data%20table%20into%20another%20worksheet.
Please help me out here.
package com.cas.ExcelTest;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Combine {
public static void main(String args[]) {
String[] files = new String[] {"Test2.xlsx","Test3.xlsx"};
XSSFWorkbook workbook = new XSSFWorkbook();
try {
for (int f = 0; f < files.length; f++) {
String file = files[f];
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook tempWorkbook = new XSSFWorkbook(inputStream);
int numOfSheets = tempWorkbook.getNumberOfSheets();
for (int i = 0; i < numOfSheets; i++) {
XSSFSheet tempSheet = tempWorkbook.getSheetAt(i);
String newSheetName = ""+f+""+tempSheet.getSheetName();
XSSFSheet sheet = workbook.createSheet(newSheetName);
Iterator<Row> itRow = tempSheet.rowIterator();
while(itRow.hasNext()) {
Row tempRow = itRow.next();
XSSFRow row = sheet.createRow(tempRow.getRowNum());
Iterator<Cell> itCell = tempRow.cellIterator();
while(itCell.hasNext()) {
Cell tempCell = itCell.next();
XSSFCell cell = row.createCell(tempCell.getColumnIndex());
switch (tempCell.getCellType()) {
case NUMERIC:
cell.setCellValue(tempCell.getNumericCellValue());
break;
case STRING:
cell.setCellValue(tempCell.getStringCellValue());
break;
case BLANK:
break;
case BOOLEAN:
break;
case ERROR:
break;
case FORMULA:
cell.setCellValue(tempCell.getNumericCellValue());
break;
case _NONE:
break;
default:
break;
}
}
}
}
}
} catch (IOException ex1) {
System.out.println("Error reading file");
ex1.printStackTrace();
}
try (FileOutputStream outputStream = new FileOutputStream("result.xlsx")) {
workbook.write(outputStream);
}
catch(Exception ex) {
System.out.println("Something went wrong");
}
}
}
My Excel files:
Test2.xlsx
Test3.xlsx
Here some columns are extra in Test3.xlsx and in both files as you can see in the heading row its all string but after that it has numeric values.
Here you have an approximation of the code you need, format it, extract functionalities to methods and check the naming of sheets.
String[] files = new String[] {"Test2.xlsx","Test3.xlsx"};
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = createSheetWithHeader(workbook);
try {
for (int f = 0; f < files.length; f++) {
String file = files[f];
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook tempWorkbook = new XSSFWorkbook(inputStream);
int numOfSheets = tempWorkbook.getNumberOfSheets();
for (int i = 0; i < numOfSheets; i++) {
XSSFSheet tempSheet = tempWorkbook.getSheetAt(i);
int indexLastDataInserted = sheet.getLastRowNum();
int firstDataRow = getFirstDataRow(tempSheet);
Iterator<Row> itRow = tempSheet.rowIterator();
while(itRow.hasNext()) {
Row tempRow = itRow.next();
if (tempRow.getRowNum() >= firstDataRow) {
XSSFRow row = sheet.createRow(indexLastDataInserted + 1);
Iterator<Cell> itCell = tempRow.cellIterator();
while(itCell.hasNext()) {
Cell tempCell = itCell.next();
XSSFCell cell = row.createCell(tempCell.getColumnIndex());
//At this point you will have to set the value of the cell depending on the type of data it is
switch (tempCell.getCellType()) {
case NUMERIC:
cell.setCellValue(tempCell.getNumericCellValue());
break;
case STRING:
cell.setCellValue(tempCell.getStringCellValue());
break;
/**
* Add your other types, here is your problem!!!!!
*/
}
}
}
}
}
}
}catch (IOException ex1) {
System.out.println("Error reading file");
ex1.printStackTrace();
}
try (FileOutputStream outputStream = new FileOutputStream("result.xlsx")) {
workbook.write(outputStream);
}
Function to get the first data row (necessary to avoid having to enter by hand where the header of each excel ends):
/**
* If the tab has a filter, it returns the row index of the filter + 1, otherwise it returns 0
* #param tempSheet
* #return index of first data row
*/
public static Integer getFirstDataRow(XSSFSheet tempSheet) {
Integer result = 0;
Boolean isAutoFilter = tempSheet.getCTWorksheet().isSetAutoFilter();
if (isAutoFilter) {
String autoFilterRef = tempSheet.getCTWorksheet().getAutoFilter().getRef();
result = new CellReference(autoFilterRef.substring(0, autoFilterRef.indexOf(":"))).getRow() + 1;
}
return result;
}
Create the sheet with header in the method:
public static XSSFSheet createSheetWithHeader(XSSFWorkbook workbook){
XSSFSheet sheet = workbook.createSheet("NEW_SHEET_NAME");
//Implement the header
[...]
return sheet;
}
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.
i m trying to merge two .xlsx files to each other in java. But i m somehow getting a NullPointerException on the line
if (cell.getSheet().getWorkbook() == mcell.getSheet()
.getWorkbook()) {
}
Any ides what could cause this error ? when i tried before merging other two files, my code worked perfectly, but now i changed the files and now getting NullPointerException. The new Files which i try to merge have 2 sheets. I just need to merge the first pages of them.
Here is my code :
public static void main(String[] args) {
try {
FileInputStream excellFile1 = new FileInputStream(new File(
"/Users/TLQ/Desktop/a.xlsx"));
FileInputStream excellFile2 = new FileInputStream(new File(
"/Users/TLQ/Desktop/b.xlsx"));
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook1 = new XSSFWorkbook(excellFile1);
XSSFWorkbook workbook2 = new XSSFWorkbook(excellFile2);
// Get first/desired sheet from the workbook
XSSFSheet sheet1 = workbook1.getSheetAt(0);
XSSFSheet sheet2 = workbook2.getSheetAt(0);
// add sheet2 to sheet1
addSheet(sheet1, sheet2);
excellFile1.close();
// save merged file
File mergedFile = new File(
"/Users/TLQ/Desktop/Albert.xlsx");
if (!mergedFile.exists()) {
mergedFile.createNewFile();
}
FileOutputStream out = new FileOutputStream(mergedFile);
workbook1.write(out);
out.close();
// mergeThemAll(mergedFile);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void addSheet(XSSFSheet mergedSheet, XSSFSheet sheet) {
// map for cell styles
Map<Integer, XSSFCellStyle> styleMap = new HashMap<Integer, XSSFCellStyle>();
// This parameter is for appending sheet rows to mergedSheet in the end
int len = mergedSheet.getLastRowNum();
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
XSSFRow row = sheet.getRow(j);
XSSFRow mrow = mergedSheet.createRow(len + j + 1);
for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
XSSFCell cell = row.getCell(k);
XSSFCell mcell = mrow.createCell(k);
if (cell.getSheet().getWorkbook() == mcell.getSheet()
.getWorkbook()) {
mcell.setCellStyle(cell.getCellStyle());
} else {
int stHashCode = cell.getCellStyle().hashCode();
XSSFCellStyle newCellStyle = styleMap.get(stHashCode);
if (newCellStyle == null) {
newCellStyle = mcell.getSheet().getWorkbook()
.createCellStyle();
newCellStyle.cloneStyleFrom(cell.getCellStyle());
styleMap.put(stHashCode, newCellStyle);
}
mcell.setCellStyle(newCellStyle);
}
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA:
mcell.setCellFormula(cell.getCellFormula());
break;
case HSSFCell.CELL_TYPE_NUMERIC:
mcell.setCellValue(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:
mcell.setCellValue(cell.getStringCellValue());
break;
case HSSFCell.CELL_TYPE_BLANK:
mcell.setCellType(HSSFCell.CELL_TYPE_BLANK);
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
mcell.setCellValue(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_ERROR:
mcell.setCellErrorValue(cell.getErrorCellValue());
break;
default:
mcell.setCellValue(cell.getStringCellValue());
break;
}
}
}
}
row.getCell(k) can return null if there is no Cell at that position. There are a few ways to work around the problem (e.g. asking the workbook to create cells on the fly), but for this case, checking against null Cells is the easiest and least resource-consuming option.
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 need to read specific column of an excel sheet and then declare the variables in java. The program that I have done reads the entire content of excel sheet. But I need to read a fixed column like C.
This is what I have done:
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class JavaApplication4
{
private String inputFile;
String[][] data = null;
public void setInputFile(String inputFile)
{
this.inputFile = inputFile;
}
public String[][] read() throws IOException
{
File inputWorkbook = new File(inputFile);
Workbook w;
try
{
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
data = new String[sheet.getColumns()][sheet.getRows()];
// Loop over first 10 column and lines
// System.out.println(sheet.getColumns() + " " +sheet.getRows());
for (int j = 0; j <sheet.getColumns(); j++)
{
for (int i = 0; i < sheet.getRows(); i++)
{
Cell cell = sheet.getCell(j, i);
data[j][i] = cell.getContents();
// System.out.println(cell.getContents());
}
}
for (int j = 0; j < data.length; j++)
{
for (int i = 0; i <data[j].length; i++)
{
System.out.println(data[j][i]);
}
}
}
catch (BiffException e)
{
e.printStackTrace();
}
return data;
}
public static void main(String[] args) throws IOException
{
JavaApplication4 test = new JavaApplication4();
test.setInputFile("C://users/admin/Desktop/Content.xls");
test.read();
}
}
Here is my excel sheet,
From a bowl of chits numbered /#v1#/ to /#v2#/ , a single chit is randomly drawn. Find the probability that the chit drawn is a number that is a multiple of /#v3#/ or /# v4#/?
I need to read this data and by matching the pattern /#v1#1, I need to declare the variables. How can I do this?
What you can do, you should first get all the columns from the sheet by using sheet.getColumns() and store all columns in a list . Then you can match get all values based on columns. or you can get for only column "C".try using below code. let me know if this works.
int masterSheetColumnIndex = sheet.getColumns();
List<String> ExpectedColumns = new ArrayList<String>();
for (int x = 0; x < masterSheetColumnIndex; x++) {
Cell celll = sheet.getCell(x, 0);
String d = celll.getContents();
ExpectedColumns.add(d);
}
LinkedHashMap<String, List<String>> columnDataValues = new LinkedHashMap<String, List<String>>();
List<String> column1 = new ArrayList<String>();
// read values from driver sheet for each column
for (int j = 0; j < masterSheetColumnIndex; j++) {
column1 = new ArrayList<String>();
for (int i = 1; i < sheet.getRows(); i++) {
Cell cell = sheet.getCell(j, i);
column1.add(cell.getContents());
}
columnDataValues.put(ExpectedColumns.get(j), column1);
}
This is the very simple and efficient code and Working as expected
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class TestExcelFile {
public static void main(String[] args) {
String envFilePath = System.getenv("AZURE_FILE_PATH");
// upload list of files/directory to blob storage
File folder = new File(envFilePath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
Workbook workbook;
//int masterSheetColumnIndex = 0;
try {
workbook = WorkbookFactory.create(new FileInputStream(envFilePath + "\\"+ listOfFiles[i].getName()));
// Get the first sheet.
Sheet sheet = workbook.getSheetAt(0);
//we will search for column index containing string "Your Column Name" in the row 0 (which is first row of a worksheet
String columnWanted = "Column_Name";
Integer columnNo = null;
//output all not null values to the list
List<Cell> cells = new ArrayList<Cell>();
// Get the first cell.
Row row = sheet.getRow(0);
//Cell cell = row.getCell(0);
for (Cell cell : row) {
// Column header names.
//System.out.println(cell.toString());
if (cell.getStringCellValue().equals(columnWanted)){
columnNo = cell.getColumnIndex();
}
}
if (columnNo != null){
for (Row row1 : sheet) {
Cell c = row1.getCell(columnNo);
if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
// Nothing in the cell in this row, skip it
} else {
cells.add(c);
//System.out.println(c);
}
}
}else{
System.out.println("could not find column " + columnWanted + " in first row of " + listOfFiles[i].getName());
}
} catch (InvalidFormatException | IOException e) {
e.printStackTrace();
}
}
}
}
}
Reading Particular column from excel file
File myFile = new File(path);
FileInputStream fis = new FileInputStream(myFile);
// Finds the workbook instance for XLSX file
XSSFWorkbook myWorkBook = new XSSFWorkbook (fis);
//XSSFWorkbook workBook = new XSSFWorkbook();
//Reading sheet at number 0 in spreadsheet(image attached for reference
Sheet sheet = myWorkBook.getSheetAt(0);
//creating a Sheet object to retrieve object
Iterator<Row> itr = sheet.iterator();//iterating over excel file
while (itr.hasNext())
{
Row row = itr.next();
Iterator<Cell> cellIterator = row.cellIterator();//iterating over each column
//Reading cell in my case column name is ppm
Cell ppmEx= row.getCell(0);
//Cell cell = cellIterator.next();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
//System.out.println(cell.getNumericCellValue() + " ");
al.add(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
//System.out.println(cell.getStringCellValue()+" ");
al.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
//System.out.println(cell.getBooleanCellValue()+" ");
al.add(cell.getBooleanCellValue());
case Cell.CELL_TYPE_BLANK:
//System.out.println("blank");
al.add("blank");
}
}
System.out.println("-");
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package xlsxreader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
/**
*
* #author khaled
*/
public class XlsxReader {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
File file = new File("C:\\Users\\khaled\\Desktop\\myXLSX file.xlsx");
Workbook workbook = WorkbookFactory.create(new FileInputStream(file));
Sheet sheet = workbook.getSheetAt(0);
int column_index_1 = 0;
int column_index_2 = 0;
int column_index_3 = 0;
Row row = sheet.getRow(0);
for (Cell cell : row) {
// Column header names.
switch (cell.getStringCellValue()) {
case "MyFirst Column":
column_index_1 = cell.getColumnIndex();
break;
case "3rd Column":
column_index_2 = cell.getColumnIndex();
break;
case "forth Column":
column_index_3 = cell.getColumnIndex();
break;
}
}
for (Row r : sheet) {
if (r.getRowNum()==0) continue;//hearders
Cell c_1 = r.getCell(column_index_1);
Cell c_2 = r.getCell(column_index_2);
Cell c_3 = r.getCell(column_index_3);
if (c_1 != null && c_1.getCellType() != Cell.CELL_TYPE_BLANK
&&c_2 != null && c_2.getCellType() != Cell.CELL_TYPE_BLANK
&&c_3 != null && c_3.getCellType() != Cell.CELL_TYPE_BLANK) {
System.out.print(" "+c_1 + " " + c_2+" "+c_3+"\n");
}
}
}
}