Check if row contains word - java

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()

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();
}
}

Get a row from excel file which contains a value

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
}
}
}

Reading and Validating Rows with Aspose JAva

I am trying to read and validate a Row with Aspose Cells Java, but I have never used ir before and de documentation is not very clear, it doesn't even show you how to read a Row. Heres what I've done so far:
public static void main(String[] args) {
String dataDir = "C:\\Users\\apoac22836\\Desktop\\";
Workbook wb = new Workbook(dataDir + "Example.xlsm");
Worksheet worksheet = wb.getWorksheets().get("BOM");
int column = 1;
for (int i = 0; i < 40; i++) {
Cell lastCell = worksheet.getCells().endCellInColumn((short) column);
for (int row = 0; row <= lastCell.getRow(); row++) {
Cell cell = worksheet.getCells().get(row, column);
System.out.println(cell.getStringValue());
}
column += 1;
System.out.println("------------------------------------------------");
}
}
I brings the value of the cells by columns.
Well, if you need to efficiently enumerate all the data (non empty values) in a range, rows, cells, you may try to use Range.iterator(), RowCollection.iterator() and Cells.iterator() method to get the iterator for specific range, initialized rows and non empty or initialized cells, see the following sample codes for your reference:
e.g
Sample code:
//Range Iterator.
Workbook book = new Workbook("sample.xlsx");
Worksheet sheet = book.getWorksheets().get(0);
Range range = sheet.getCells().getMaxDisplayRange();//You may also create your desired range (in the worksheet) using, e.g sheet.getCells().createRange("A1", "J11");
Iterator rangeIterator = range.iterator();
while(rangeIterator.hasNext())
{
Cell cell = (Cell)rangeIterator.next();
System.out.println(cell.getName() + " is not empty");
}
//Cells Iterator.
Workbook workbook = new Workbook("Book1.xls");
Worksheet sheet = workbook.getWorksheets().get(0);
Cells cells = sheet.getCells();
//Get the iterator from Cells collection
Iterator cellIterator = cells.iterator();
//Traverse cells in the collection
while (cellIterator.hasNext()) {
Cell cell = (Cell) cellIterator.next();
System.out.println(cell.getName() + " " + cell.getValue());
}
//Rows collection Iterator.
String filePath = "c:\\source.xlsx";
Workbook workbook = new Workbook(filePath);
Worksheet worksheet = workbook.getWorksheets().get(0);
RowCollection rows = worksheet.getCells().getRows();
Object obj = rows.iterator().next();
Iterator<Row> rowIterator = worksheet.getCells().getRows().iterator();
while(rowIterator.hasNext())
{
Row r = rowIterator.next();
Iterator<Cell> cellIterator = r.iterator();
while(cellIterator.hasNext())
{
Cell cell= cellIterator.next();
System.out.println(cell.getStringValue());
}
}
Hope, this helps a bit.
I am working as support developer/Evangelist at Aspose.

setCellValue not working

i can't set the value of cell ,it works if i try this
if(1==1){
celltofill.setCellValue("test");
}
but once it enters the if condition it displays what's in syso but doesn't insert values in the cell.
any ideas about how can i solve this isssue?
here is my code:
public class testexcel {
public static void main(String[] args) throws InvalidFormatException, IOException, ParseException{
FileInputStream fis = new FileInputStream("D:\\test6.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
FileOutputStream fos=new FileOutputStream("D:\\edit6.xlsx");
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFSheet sheet2 = workbook.getSheetAt(1);
for(int i=1; i <= sheet.getLastRowNum(); i++) {
for(int i1=1;i1<sheet2.getLastRowNum();i1++){
Row row = sheet.getRow(i);
Cell cell = row.getCell(2);
Row row2 = sheet2.getRow(i1);
Cell cell2 = row2.getCell(0);
Cell celltofill= row.createCell(5);
Cell cellres= row2.getCell(1);
if((cell.getStringCellValue()).equals(cell2.getStringCellValue())){
System.out.println((cell.getStringCellValue())+" equals "+cell2.getStringCellValue());
celltofill.setCellType(Cell.CELL_TYPE_STRING);
System.out.println("cell filled with "+cellres.getStringCellValue());
celltofill.setCellValue(cellres.getStringCellValue());
}
}
}
workbook.write(fos);
fos.close();
}
}
row.createCell(5) does exactly what it says. It creates a new empty cell every time it is called. And you are calling it for every row in sheet2 again and again although it is a cell in sheet. So even if the criterions are not fullfilled, the new empty cell is been created already in your code.
Maybe:
...
for(int i=1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
Cell cell = row.getCell(2);
Cell celltofill= row.getCell(5);
if (celltofill == null) celltofill = row.createCell(5);
for(int i1=1;i1<sheet2.getLastRowNum();i1++){
Row row2 = sheet2.getRow(i1);
Cell cell2 = row2.getCell(0);
Cell cellres= row2.getCell(1);
...
will be more what you want?

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