Get a row from excel file which contains a value - java

I need to get a row which contains value in column 1 in my excel file using Java
I need to search column when find cell then get the row which contains searched cell

FileInputStream fis = new FileInputStream(new File(filepath));
XSSFWorkbook workBook = new XSSFWorkbook (fis);
XSSFSheet sheet = workBook.getSheetAt (0);
List<XSSFRow> filteredRows = new ArrayList<XSSFRow>();
Iterator<Row> rows= sheet.rowIterator();
while (rows.hasNext ()){
XSSFRow row = (XSSFRow) rows.next ();
for(Cell cell : row) {
if(cell.getColumnIndex() == 1) {
// process a cell in column 1
if (cell.getStringCellValue()!=null){
String val = cell.getStringCellValue();
if (val.equals(""))
//You will find valid value in variable val
}
}
}

Related

Custom Data Validation to thousands of cells using apache poi

I am creating an excel sheet in Java which has more than 10k records. For a particular column, I want to set a validation to all cells in that column that it can either be of "NEW_RULE-x" type where x >= 1 (NEW_RULE-1, NEW_RULE-2,..., etc.) or "x" type (1,2,...,etc.)
So manually in excel, I figured out applying below Custom Validation to cell (let's say D3) :
"=OR(AND(LEFT(D3,9)="NEW_RULE-",MID(D3,10,1)>="1"),OR(AND(D3>=1,D3<=999999)))".
If I want to apply it to D4, then the validation formula will have D4 instead of D3. Is their a generic way to do it for entire D column, so that I don't have to apply for each cell in Java code while iterating records? Below is the code to generate a quick excel sheet with data validation at D3 cell.
String filePath = "D\\mysheet.xlsx";
File file = new File(filePath);
XSSFWorkbook workbook = new XSSFWorkbook();
FileOutputStream fos;
try {
XSSFSheet sheet = workbook.createSheet();
for (int i = 0; i <= 5; i++) {
XSSFRow row = sheet.getRow(i);
if(row == null)
row = sheet.createRow(i);
XSSFCell cell=row.getCell(0);
if(cell == null)
cell = row.createCell(0, XSSFCell.CELL_TYPE_STRING);
cell.setCellValue("Keyword" +i);
cell=row.getCell(1);
if(cell == null)
cell = row.createCell(1, XSSFCell.CELL_TYPE_STRING);
cell.setCellValue("PASS" +i);
System.out.println("1");
}
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper.createCustomConstraint(
"=OR(AND(LEFT(D3,9)=\"NEW_RULE-\",MID(D3,10,1)>=\"1\"),OR(AND(D3>=1,D3<=999999)))");
//=OR(AND(LEFT(D3,9)="NEW_RULE-",MID(D3,10,1)>="1"),OR(AND(D3>=1,D3<=999999)))
CellRangeAddressList addressList = new CellRangeAddressList(2,2,3,3);
XSSFDataValidation dataValidation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint, addressList);
sheet.addValidationData(dataValidation);
fos = new FileOutputStream(filePath);
workbook.write(fos);
fos.close();
}finally{
}
}```
At first: Do not put the equals sign = in front on formula strings when set via apache poi. The equals sign is not stored in Excel's storage. It only is visible in GUI.
And when ever formulas are used , even in conditional formatting and data validation, cell references can be relativ or absolut. For example A1 is a relativ reference while $A$1 is a absolut reference. So as you are using only relative references in your formula, the references will be adjusted to new cells in sheet. For example LEFT(D1,9)="NEW_RULE-" in cell D1 will be LEFT(D2,9)="NEW_RULE-" in cell D2 and LEFT(D3,9)="NEW_RULE-" in cell D3 and so on.
So the formula string "OR(AND(LEFT($D1,9)=\"NEW_RULE-\",MID($D1,10,1)>=\"1\"),OR(AND($D1>=1,$D1<=999999)))" can be adopted for the cells D1:D1000 and will always be correct for the current relative row in absolute column D.
Complete example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddressList;
class CreateExcelDataValidation {
public static void main(String[] args) throws Exception {
//Workbook workbook = new HSSFWorkbook(); String filePath = "./mysheet.xls";
Workbook workbook = new XSSFWorkbook(); String filePath = "./mysheet.xlsx";
Sheet sheet = workbook.createSheet();
for (int i = 0; i <= 5; i++) {
Row row = sheet.getRow(i);
if (row == null) row = sheet.createRow(i);
Cell cell = row.getCell(0);
if (cell == null) cell = row.createCell(0);
cell.setCellValue("Keyword" +i);
cell = row.getCell(1);
if (cell == null) cell = row.createCell(1);
cell.setCellValue("PASS" +i);
}
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
DataValidationConstraint dvConstraint = dvHelper.createCustomConstraint("OR(AND(LEFT($D1,9)=\"NEW_RULE-\",MID($D1,10,1)>=\"1\"),OR(AND($D1>=1,$D1<=999999)))");
CellRangeAddressList addressList = new CellRangeAddressList(0, 1000, 3, 3);
DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
if (workbook instanceof XSSFWorkbook) validation.setShowErrorBox(true);
sheet.addValidationData(validation);
FileOutputStream out = new FileOutputStream(filePath);
workbook.write(out);
workbook.close();
out.close();
}
}

How to get cell value from the cell which consists of formula in excel xls file

I am writing java code to read excel file and to create an object from that but one column consists of formula when I read cell formula is coming in value field instead of value
I tried to get from cell index
I tried to get value from iterator(hasnext()) method :
like:
public static void CheckDuplicate(File file) throws Exception {
Set newReordsList = new LinkedHashSet();
LinkedHashMap<String, DataCleansingObject> lhm = new LinkedHashMap<String, DataCleansingObject>();
FileInputStream fis = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet spreadsheet = workbook.getSheetAt(0);
HSSFRow row;
Iterator< Row> rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext()) {
row = (HSSFRow) rowIterator.next();
if(row.getRowNum() == 0) {
continue;
}
DataCleansingObject dataObj = new DataCleansingObject();
Iterator< Cell> cellIterator = row.cellIterator();
String key = "";
if (cellIterator.hasNext()) {
dataObj.setDocType(row.getCell(1).toString());
dataObj.setDocNo(row.getCell(2).toString());
dataObj.setDocVer(Long.parseLong(row.getCell(3).toString()));
dataObj.setDocPart(row.getCell(4).toString());
dataObj.setDocLang(row.getCell(5).toString());
dataObj.setDocRev(row.getCell(6).toString());
dataObj.setDocStatus(row.getCell(7).toString());
dataObj.setDocSD(row.getCell(8).toString());
dataObj.setDocLD(row.getCell(9).toString());
dataObj.setDocChangeNumber(row.getCell(10).toString());
key = row.getCell(1).toString() + "_" + row.getCell(2).toString() + "_" + row.getCell(3).toString() + "_" + row.getCell(4).toString();
}
lhm.put(key, dataObj);
}
fis.close();
copyInExcel(newReordsList);
}
When ever I call below line
Long.parseLong(row.getCell(3).toString())
I need to get long value not formula in that cell

Check if row contains word

I have a spreadsheet and I only want to select rows that have a specific word in one column and another word in another column. At the moment I am only able to check for the word in any cell in the row. How can I check for the presence of the word in a cell in a specific column?
Here is my code
FileInputStream fis = new FileInputStream(new File(filepath));
XSSFWorkbook workBook = new XSSFWorkbook (fis);
XSSFSheet sheet = workBook.getSheetAt (0);
List<XSSFRow> filteredRows = new ArrayList<XSSFRow>();
Iterator<Row> rows= sheet.rowIterator();
while (rows.hasNext ()){
XSSFRow row = (XSSFRow) rows.next ();
Iterator<Cell> cells = row.cellIterator ();
while (cells.hasNext ()){
XSSFCell cell = (XSSFCell) cells.next ();
if (cell.toString().contains("Ginko")) {
filteredRows.add(row);
break;
}
}
}
You can check if a cell is in a specific column by calling cell.getColumnIndex() == columnNumber. For example:
for(Cell cell : row) {
if(cell.getColumnIndex() == 1) {
// process a cell in column 1
}
}
Source: https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Cell.html#getColumnIndex()

Covert XLSX row into string and add to array

I am trying to get a basic java program to read from a xlsx file and put each row into an arrayList as a string, where later on I will then split that String up of that row.
Below is my code, however i'm trying to figure out where I have gone wrong as it doesn't appear to be doing anything.
List<String> text = new ArrayList<String>();
Workbook wb = WorkbookFactory.create(new File("input.xlsx"));
DataFormatter fmt = new DataFormatter();
Sheet s = wb.getSheetAt(0);
for (Row r : s) {
StringBuffer sb = new StringBuffer();
for (Cell c : r) {
if (sb.length() > 0) sb.append(" - ");
sb.append(fmt.formatCell(c));
}
text.append(sb.toString());
}
Any help would be appreciated.
You are not reading any cell. See this example:
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
//..
FileInputStream file = new FileInputStream(new File("C:\\test.xlsx"));
//Get the workbook instance for XLS file
XSSFWorkbook workbook = new XSSFWorkbook (file);
//Get first sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

How to populate an Excel sheet with the data from an arraylist using Apache POI

How to populate an Excel sheet with the data from an arraylist using Apache POI?
public String exporttoexcel(UserDetails user) throws Exception {
System.out.print("Inside serviceimpl.ExportToExcel method");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow((short)0);
List<UserDetails> lstUserDetail = getUserDetailList();
for (int i=0; i<lstUserDetail.size(); i++) {
UserDetails lstUserDetail1 = lstUserDetail.get(i);
String a=lstUserDetail1.getStrUserName();
System.out.print("useridddd is"+a);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue(lstUserDetail1.getStrUserId());
cell.setCellValue(lstUserDetail1.getStrUserName());
cell.setCellValue(lstUserDetail1.getStrEMail());
cell.setCellValue(lstUserDetail1.getStrUserStatus());
cell.setCellValue(lstUserDetail1.getStrUserRole());
}
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
System.out.print("file created");
return null;
}
You have created one single cell and entering all the values in a same single cell each time.
You need to take two loops. One for iterating through row and another for iterating through column. Though I have not tested... use code like below.
for(int RowNum=0; RowNum<MaxArrayLength;RowNum++){
HSSFRow row = sheet.createRow(RowNum);
for(int ColNum=0; ColNum<ArrayWidth;ColNum++){
HSSFCell cell = row.createCell(ColNum);
cell.setCellValue(ArrayList[RowNum][ColNum]);
}
}
FileOutputStream fileOut = new FileOutputStream("your file path");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("sheet name");
try {
//creating the headers
Row row = sheet.createRow(0);
row.createCell(0).setCellValue("name");
row.createCell(1).setCellValue("Name1");
row.createCell(2).setCellValue("name2");
//get the list which u want
List<String> list = getNamesList();
int rowNum = 1;
for (Name name : list ) {
Row row1 = sheet.createRow(rowNum++);
row1.createCell(0).setCellValue((name.get..));
}
workbook.write(fileOut);
}

Categories