简体   繁体   中英

How to make a table in console in Java and POI using printf/formatter with generic data type

I am fairly new to stack overflow and I am trying to make a table in my console, but when I try to use printf for padding or java's Formatter , I can't seem to fit it in my code as the cell could be any type.

package com.codeblit.IO;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

public class ExcelReader {

    private XSSFWorkbook workbook;
    private XSSFSheet sheet;
    private DataFormatter formatter;
    private Cell cell;
    private int rowCount, columnCount, rowHeight;

    public ExcelReader(String filePath) {
        init(filePath);
    }

    private void init(String filePath){
        File src = new File(filePath);

        //POI = Poor Obfuscation Implementation
        //XSSF = use of xlsx format, from 2007 onwards
        //HSSF = use of xls format,  before 2007 and older
        //All indexes start at 0 including: sheets, columns, rows etc.

        try {
            workbook = new XSSFWorkbook(src); //The full workbook created from file
        } catch (IOException ioe){
            System.err.println("[ERROR]; Workbook couldn't be created from file due to IO!");
            ioe.printStackTrace();
        } catch (InvalidFormatException ife){
            System.err.println("[ERROR]: Workbook couldn't be created by file due to invalid formats!");
            ife.printStackTrace();
        }

        formatter = new DataFormatter();
    }

    public String readAsString(int sheetIndex, int row, int column){
        sheet = workbook.getSheetAt(sheetIndex); //The sheet at sheetIndex in the excel workbook
        cell = sheet.getRow(row).getCell(column); //select the row and column, get the cell

        return formatter.formatCellValue(cell); //return the value of the cell as a string even if it is numeric to avoid errors
    }

    public double readAsNumeric(int sheetIndex, int row, int column) {
        sheet = workbook.getSheetAt(sheetIndex); //The sheet at sheetIndex in the excel workbook

        return sheet.getRow(row).getCell(column).getNumericCellValue(); //select the row and column, and get the value as a double
    }

    public void printSheet(int sheetIndex){
        sheet = workbook.getSheetAt(sheetIndex);
        Iterator iterator = sheet.rowIterator(); //think of it as j for columns in multi dimensional arrays
        Row row; //the current row
        Cell cell;

        while (iterator.hasNext()) { //detect if there is a next column, this works as
            row = (Row) iterator.next();
            System.out.print("\n");

            for(int i = 0; i <= getRowCount(); i++){
                cell = row.getCell(i); //the current cell in the row
                System.out.print("\t\t\t");


                switch (cell.getCellType()) {
                    case STRING:
                        System.out.print(cell.getStringCellValue());
                        break;
                    case NUMERIC:
                        if(DateUtil.isCellDateFormatted(cell))
                            System.out.println(cell.getDateCellValue());
                        System.out.print(cell.getNumericCellValue());
                        break;
                    case BOOLEAN:
                        System.out.print(cell.getBooleanCellValue());
                        break;
                    case FORMULA:
                        System.out.print(cell.getCellFormula());
                        break;
                    case ERROR:
                        System.out.print(cell.getErrorCellValue());
                        break;
                    default:
                        System.out.print("Unidentified Cell Value: " + cell.getCellType());
                }
            }
        }
    }

    //********** GETTERS && SETTERS **********

    public int getRowCount() {
        //I set it here and not initialize so that every time we change the sheet and call this method again it will change the value instead of giving it the same one
        rowCount = sheet.getLastRowNum();
        return rowCount;
    }

//    1. int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();
//    2. int noOfColumns = sh.getRow(0).getLastCellNum();

//    There is a fine difference between them:
//    Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9) it will replace it with blank lines/spaces
//    Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'

    public int getColumnCount(int rowIndex) {
        //I set it here and not initialize so that every time we change the sheet and call this method again it will change the value instead of giving it the same one
        columnCount = sheet.getRow(rowIndex).getLastCellNum();
        return columnCount;
    }

    public int getRowHeight(Row row) {
        rowHeight = row.getHeight();
        return rowHeight;
    }

}

Where the emphasis is:

while (iterator.hasNext()) { //detect if there is a next column, this works as
    row = (Row) iterator.next();
    System.out.print("\n");

    for(int i = 0; i <= getRowCount(); i++){
        cell = row.getCell(i); //the current cell in the row
        System.out.print("\t\t\t");


        switch (cell.getCellType()) {
            case STRING:
                System.out.print(cell.getStringCellValue());
                break;
            case NUMERIC:
                if(DateUtil.isCellDateFormatted(cell))
                    System.out.println(cell.getDateCellValue());
                System.out.print(cell.getNumericCellValue());
                break;
            case BOOLEAN:
                System.out.print(cell.getBooleanCellValue());
                break;
            case FORMULA:
                System.out.print(cell.getCellFormula());
                break;
            case ERROR:
                System.out.print(cell.getErrorCellValue());
                break;
            default:
                System.out.print("Unidentified Cell Value: " + cell.getCellType());
        }
    }
}

edit: Here is my current output: 我当前的输出

I want it to be organized like the first column

Thanks.

I solved my problem I needed to create a method:

public void printSheetAsString(int sheetIndex){
    sheet = workbook.getSheetAt(sheetIndex);
    Row row;

    //a row iterator which iterates through rows in a specified sheet
    for(Iterator<Row> rowIterator = sheet.rowIterator(); rowIterator.hasNext();){
        row = rowIterator.next(); //store the next element into the variable "row"

        //a cell iterator which iterates through cells in the sheet's rows
        for(Iterator<Cell> cellIterator = row.cellIterator(); cellIterator.hasNext();){
            cell = cellIterator.next(); //store the next element into the variable "cell"
            cell.setCellType(CellType.STRING); //set all the cells to type string so that we can print them out easily

            //print "%" for place holder/variable, "-" for left justified table, "30" for spaces between each column, "s" for string
            //this will print the cell then move to the next cell, print that cell, so on, till we reach the next row, which repeats the process, them move to next row, and so on till rowIterator.hasNext() returns false
            System.out.printf("%-30s", cell.getStringCellValue());
        }

        System.out.println();
    }
}

Where the emphasis is:

//print "%" for place holder/variable, "-" for left justified table, "30" for spaces between each column, "s" for string
//this will print the cell then move to the next cell, print that cell, so on, till we reach the next row, which repeats the process, them move to next row, and so on till rowIterator.hasNext() returns false
System.out.printf("%-30s", cell.getStringCellValue());

This finally prints the output: 正确输出

I then made another method which prints the variables properly instead of converting them to a string and using deprecated methods:

public void printSheet(int sheetIndex){
        sheet = workbook.getSheetAt(sheetIndex);
        Row row;

        for(Iterator<Row> rowIterator = sheet.rowIterator(); rowIterator.hasNext();){
            row = rowIterator.next();

            for(Iterator<Cell> cellIterator = row.cellIterator(); cellIterator.hasNext();){
                cell = cellIterator.next();

                switch (cell.getCellType()) {
                    case STRING:
                        System.out.printf("%-30s", cell.getStringCellValue());
                        break;
                    case NUMERIC:
                        if(DateUtil.isCellDateFormatted(cell))
                            System.out.printf("%-30s", cell.getDateCellValue().toString());
                        System.out.printf("%-30f", cell.getNumericCellValue());
                        break;
                    case BOOLEAN:
                        System.out.printf("%-30b", cell.getBooleanCellValue());
                        break;
                    case FORMULA:
                        System.out.printf("%-30s", cell.getCellFormula());
                        break;
                    case ERROR:
                        System.out.printf("%-30x", cell.getErrorCellValue());
                        break;
                    default:
                        System.err.print("[ERROR]: Unidentified Cell Value: " + cell.getCellType());
                }
            }

            System.out.println();
        }
    }
}

This also gives the same result.

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM