Skip to content
Advertisement

Workbook in java to find all words in sheet starting with “$” in a xlsx file

I’m working on an excel sheet in which I have multiple columns, which holds multiple text values including variables starting with $. I’m writing a Java code using workbook to read xlsx files. Since I have never used it before, may someone tell me how to achive this task using same. My code structure is here:

package com.demo.ExcelProject;

import java.io.File;

import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.CellRange;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;

public class CreateResult {

    public static void main(String[] args) {
        try {
            //Create a workbook
            Workbook workbook = WorkbookFactory.create(new File("template.xlsx"));

            //Get the first worksheet
            CTWorksheet worksheet = (CTWorksheet) workbook.getSheetAt(0);
            
            //Find the text string "$"
            
            //Save the document to file
            workbook.saveToFile("output.xlsx");
        }
        catch(Exception e) {
            e.printStackTrace();
        }

    }

}

Some familier ones, please guide me.

Advertisement

Answer

well, you will need iterator to iterate over Row (this also needs .next() ) and iterator to iterate over cell. as you iterate over cell, you get the next cell with .next(), and it should look something like this

Iterator<Row> iterator = inputSheet.iterator();
    while (iterator.hasNext()){
        Row nextRow = iterator.next();
        Iterator<Cell> cellIterator = nextRow.cellIterator(); 
        //iterator() or cellIterator() both ok
        while (cellIterator.hasNext()){
            Cell cell = cellIterator.next();
            String cellVal = cell.getStringCellValue();
            if (cellVal.startsWith("$")){
                //do something
            }
        }
    }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement