如何使用具有通用数据类型的printf/formatter在Java和POI的控制台中生成表

如何使用具有通用数据类型的printf/formatter在Java和POI的控制台中生成表,java,apache-poi,printf,Java,Apache Poi,Printf,我对堆栈溢出相当陌生,我正在尝试在控制台中创建一个表,但当我尝试使用printf填充或java的格式化程序时,我似乎无法将其放入代码中,因为单元格可以是任何类型 package com.codeblit.IO; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.X

我对堆栈溢出相当陌生,我正在尝试在控制台中创建一个表,但当我尝试使用
printf
填充或java的
格式化程序时,我似乎无法将其放入代码中,因为单元格可以是任何类型

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

}
package com.codeblit.IO;
导入org.apache.poi.openxml4j.exceptions.InvalidFormatException;
导入org.apache.poi.ss.usermodel.*;
导入org.apache.poi.xssf.usermodel.xssfheet;
导入org.apache.poi.xssf.usermodel.xssf工作簿;
导入java.io.File;
导入java.io.IOException;
导入java.util.Iterator;
公共课优秀读者{
私人XSSF工作簿;
私人XSSF表;
专用数据格式化程序;
私人小区;
私有int行数、列数、行高;
公共ExcelReader(字符串文件路径){
init(文件路径);
}
私有void init(字符串文件路径){
文件src=新文件(文件路径);
//POI=模糊处理实现不佳
//XSSF=从2007年起使用xlsx格式
//HSSF=使用xls格式,2007年及以前
//所有索引从0开始,包括:图纸、列、行等。
试一试{
工作簿=新XSSF工作簿(src);//从文件创建的完整工作簿
}捕获(ioe异常ioe){
System.err.println(“[ERROR];由于IO原因,无法从文件创建工作簿!”);
ioe.printStackTrace();
}捕获(无效格式异常){
System.err.println(“[错误]:由于格式无效,无法通过文件创建工作簿!”);
ife.printStackTrace();
}
格式化程序=新的数据格式化程序();
}
公共字符串readAsString(int sheetIndex、int行、int列){
sheet=工作簿.getSheetAt(sheetIndex);//excel工作簿中sheetIndex处的工作表
cell=sheet.getRow(row).getCell(column);//选择行和列,获取单元格
return formatter.formatCellValue(cell);//以字符串形式返回单元格的值,即使它是数值也可以,以避免错误
}
公共双读数字(int sheetIndex、int行、int列){
sheet=工作簿.getSheetAt(sheetIndex);//excel工作簿中sheetIndex处的工作表
return sheet.getRow(row).getCell(column).getNumericCellValue();//选择行和列,并以双精度形式获取值
}
公共作废打印页(整版索引){
sheet=工作簿.getSheetAt(sheetIndex);
迭代器迭代器=sheet.rowIterator();//将其视为多维数组中列的j
Row Row;//当前行
细胞;
虽然(iterator.hasNext()){//detect是否有下一列,但其工作原理如下
row=(row)迭代器.next();
系统输出打印(“\n”);

对于(int i=0;i我解决了我的问题,我需要创建一个方法:

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();
    }
}
最后打印输出:

然后,我制作了另一种方法,正确地打印变量,而不是将它们转换为字符串并使用不推荐使用的方法:

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();
        }
    }
}
public void打印页(int sheetIndex){
sheet=工作簿.getSheetAt(sheetIndex);
行行;
for(迭代器rowIterator=sheet.rowIterator();rowIterator.hasNext();){
行=行迭代器。下一步();
for(迭代器cellIterator=row.cellIterator();cellIterator.hasNext();){
cell=cellIterator.next();
开关(cell.getCellType()){
大小写字符串:
System.out.printf(“%-30s”,cell.getStringCellValue());
打破
大小写数字:
if(DateUtil.isCellDateFormatted(单元格))
System.out.printf(“%-30s”,cell.getDateCellValue().toString());
System.out.printf(“%-30f”,cell.getNumericCellValue());
打破
大小写布尔值:
System.out.printf(“%-30b”,cell.getBooleanCellValue());
打破
案例公式:
System.out.printf(“%-30s”,cell.getCellFormula());
打破
案例错误:
System.out.printf(“%-30x”,cell.getErrorCellValue());
打破
违约:
System.err.print(“[ERROR]:未识别的单元格值:”+Cell.getCellType());
}
}
System.out.println();
}
}
}
这也给出了同样的结果


谢谢!

我解决了创建方法所需的问题:

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();
    }
}
最后打印输出:

然后,我制作了另一种方法,正确地打印变量,而不是将它们转换为字符串并使用不推荐使用的方法:

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();
        }
    }
}
public void打印页(int sheetIndex){
sheet=工作簿.getSheetAt(sheetIndex);
行行;
for(迭代器rowIterator=sheet.rowIterator();rowIterator.hasNext();){
行=行迭代器。下一步();
for(迭代器cellIterator=row.cellIterator();cellIterator.hasNext();){
cell=cellIterator.next();
开关(cell.getCellType()){
大小写字符串:
System.out.printf(“%-30s”,cell.getStringCellValue());
打破
大小写数字:
if(DateUtil.isCellDateFormatted(单元格))
System.out.printf(“%-30s”,cell.getDateCellValue().toString());
System.out.printf(“%-30f”,cell.getNumericCellValue());
打破
大小写布尔值:
System.out.printf(“%-30b”,cell.getBooleanCellValue());
打破
案例公式:
System.out.printf(“%-30s”),cell.getCellFormu