skip to Main Content

Im having difficulty with using Apache POI API. Im trying to import an excel them only select certain rows and cells to extract from the import. Im currently able to import, but i cant extract certain cell. Here is code:

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;

import java.io.File;
import java.io.IOException;

public class ExcelReader {
    public static final String path = "C:/Users/xxxx/Documents/import testing.xlsx";

    public static void main(String[] args) throws IOException, InvalidFormatException {

        // Create a workbook with data from excel file
        Workbook workbook = WorkbookFactory.create(new File(path));

        // Save sheets from workbook
        Sheet sheet = workbook.getSheetAt(0);

        // Make sure the data is saved in string format using a data formatter
        DataFormatter dataFormatter = new DataFormatter();

        // Iterate through cells and columns, printing their content
        System.out.println("nnThe content of the excel file: " + path + "n");
        String cellContent;
        for (Row row: sheet) {
            for(Cell cell: row) {
                cellContent = dataFormatter.formatCellValue(cell);
                if(cellContent == null || cellContent.trim().isEmpty()){
                    // Give the empty cells the content "empty", to make it easy to filter out later on
                    cellContent = "empty";
                }
                System.out.print(cellContent + "t");
            }
            CellReference cellReference = new CellReference("A11");
            XSSFRow rowT = sheet.getRow(cellReference.getRow());
            if (rowT != null) {
                XSSFCell cell = rowT.getCell(cellReference.getCol());
            }
            System.out.println();

        }
        // Close the connection to the workbook
        workbook.close();
    }
}

2

Answers


  1. Changing Workbook to XSSFWorkbook and Sheet to XSSFSheet seems to fix the compilation issue.

    XSSFWorkbook workbook = new XSSFWorkbook(new File(path));
    

    and

    XSSFSheet sheet = workbook.getSheetAt(0);
    
    Login or Signup to reply.
  2. try with this for get “A11” cell

    XSSFCell cell = sheet.getRow(10).getCell(0); // 10 = id of the 11th row, 0 = id of the 1st (A) column
    

    or

    XSSFCell cell = sheet.getRow(10).getCell(CellReference.convertColStringToIndex("A"));
    

    create cell reference for B12

    CellReference cr = new CellReference("B12");
    row = mySheet.getRow(cr.getRow());
    cell = row.getCell(cr.getCol());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search