java poi reader

简介: 注意:(1)判断行的最大数量建议使用sheet.getLastRowNum();(2)判断每行最大列数建议使用row.getLastCellNum();   getPhysicalNumberOfRows()获取的是物理行数,也就是不包括那些空行(隔行)的情况。

 注意:
(1)判断行的最大数量建议使用sheet.getLastRowNum();
(2)判断每行最大列数建议使用row.getLastCellNum();

 

getPhysicalNumberOfRows()获取的是物理行数,也就是不包括那些空行(隔行)的情况。

getLastRowNum()获取的是最后一行的编号(编号从0开始)。

int org.apache.poi.ss.usermodel.Sheet.getPhysicalNumberOfRows()

Returns the number of physically defined rows (NOT the number of rows in the sheet)

 

int org.apache.poi.ss.usermodel.Sheet.getLastRowNum()

Gets the last row on the sheet

Returns:
last row contained in this sheet (0-based)





public class ImportExcel {
    
    private static Logger log = LoggerFactory.getLogger(ImportExcel.class);
            
    /**
     * 工作薄对象
     **/
    private Workbook wb;
    
    /**
     * 工作表对象
     **/
    private Sheet sheet;
    
    /**
     * 标题行号
     */
    private int headerNum;
    
    /**
     * 构造函数
     * @param path 导入文件,读取第1个工作表
     * @param headerNum 标题行号,数据行等于标题行号+1
     * @throws InvalidFormatException 
     * @throws IOException 
     */
    public ImportExcel(String fileName, int headerNum) 
            throws InvalidFormatException, IOException {
        this(new File(fileName), headerNum);
    }
    
    /**
     * 构造函数
     * @param path 导入文件对象,读取第1个工作表
     * @param headerNum 标题行号,数据行等于标题行号+1
     * @throws InvalidFormatException 
     * @throws IOException 
     */
    public ImportExcel(File file, int headerNum) 
            throws InvalidFormatException, IOException {
        this(file, headerNum, 0);
    }

    /**
     * 构造函数
     * @param path 导入文件
     * @param headerNum 标题行号,数据行等于标题行号+1
     * @param sheetIndex 工作表编号,以0开始
     * @throws InvalidFormatException 
     * @throws IOException 
     */
    public ImportExcel(String fileName, int headerNum, int sheetIndex) 
            throws InvalidFormatException, IOException {
        this(new File(fileName), headerNum, sheetIndex);
    }
    
    /**
     * 构造函数
     * @param path 导入文件对象
     * @param headerNum 标题行号,数据行等于标题行号+1
     * @param sheetIndex 工作表编号,以0开始、
     * @throws InvalidFormatException 
     * @throws IOException 
     */
    public ImportExcel(File file, int headerNum, int sheetIndex) 
            throws InvalidFormatException, IOException {
        this(file.getName(), new FileInputStream(file), headerNum, sheetIndex);
    }
    
    /**
     * 构造函数
     * @param file 导入文件对象
     * @param headerNum 标题行号,数据行等于标题行号+1
     * @param sheetIndex 工作表编号,以0开始、 
     * @throws InvalidFormatException 
     * @throws IOException 
     */


    /**
     * 构造函数
     * @param path 导入文件对象
     * @param headerNum 标题行号,数据行等于标题行号+1
     * @param sheetIndex 工作表编号,以0开始、
     * @throws InvalidFormatException 
     * @throws IOException 
     */
    public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex) 
            throws InvalidFormatException, IOException {
        if (StringUtils.isBlank(fileName)){
            throw new RuntimeException("导入文档为空!");
        }else if(fileName.toLowerCase().endsWith("xls")){    
            this.wb = new HSSFWorkbook(is);    
        }else if(fileName.toLowerCase().endsWith("xlsx")){  
            this.wb = new XSSFWorkbook(is);
        }else{  
            throw new RuntimeException("文档格式不正确?");
        }  
        if (this.wb.getNumberOfSheets()<sheetIndex){
            throw new RuntimeException("文档中没有工作表!");
        }
        this.sheet = this.wb.getSheetAt(sheetIndex);
        this.headerNum = headerNum;
        log.debug("Initialize success.");
    }
    
    /**
     * 获取行对象
     * @param rownum
     * @return
     */
    public Row getRow(int rownum){
        return this.sheet.getRow(rownum);
    }

    /**
     * 获取数据行号
     * @return
     */
    public int getDataRowNum(){
        return headerNum+1;
    }
    
    /**
     * 获取工作表中的最后一行的行号,以0开始
     * @return
     */
    public int getLastDataRowNum(){
        return this.sheet.getLastRowNum();
    }
    
    /**
     * 获取一行记录总的列数
     * @return
     */
    public int getLastCellNum(){
        return this.getRow(headerNum).getLastCellNum();
    }
    
    /**
     * 获取单元格的值
     * @param row 获取的行
     * @param column 获取单元格列号
     * @return 单元格的值
     */
    public Object getCellValue(Row row, int column){
        Object val = "";
        try{
            Cell cell = row.getCell(column);
            if (cell != null){
                if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
                    val = cell.getNumericCellValue();
                }else if (cell.getCellType() == Cell.CELL_TYPE_STRING){
                    val = cell.getStringCellValue();
                }else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA){
                    val = cell.getCellFormula();
                }else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){
                    val = cell.getBooleanCellValue();
                }else if (cell.getCellType() == Cell.CELL_TYPE_ERROR){
                    val = cell.getErrorCellValue();
                }
            }
        }catch (Exception e) {
            return val;
        }
        return val;
    }
    /**
     * 导入测试
     */
    public static void main(String[] args) throws Throwable {
        ImportExcel ei = new ImportExcel("import.xls", 0);
        System.out.println(ei.getLastDataRowNum());
        System.out.println(ei.getDataRowNum());
        
        for (int i = ei.getDataRowNum(); i <= ei.getLastDataRowNum(); i++) {
            Row row = ei.getRow(i);
            System.out.println("Row num:"+i);
            for (int j = 0; j < ei.getLastCellNum(); j++) {
                Object val = ei.getCellValue(row, j);
                System.out.print(val+", ");
            }
            System.out.print("\n");
        }
        
    }

}

 

相关文章
|
5月前
|
Java
【java】poi 设置允许西文在单词中间换行
【java】poi 设置允许西文在单词中间换行
|
Java Maven
【Java用法】使用poi写Java代码导出Excel文档的解决方案
【Java用法】使用poi写Java代码导出Excel文档的解决方案
78 0
|
18天前
|
Java Apache
Apache POI java对excel表格进行操作(读、写) 有代码!!!
文章提供了使用Apache POI库在Java中创建和读取Excel文件的详细代码示例,包括写入数据到Excel和从Excel读取数据的方法。
25 0
|
1月前
|
Java Apache Maven
Java中使用poi+poi-tl实现根据模板导出word文档
这个过程不仅简化了文档生成的工作,而且保证了生成文档的一致性与准确性,特别适合于那些需要生成大量文档的自动化场景。通过以上步骤,Java开发人员可以实现高效、可靠的Word文档导出功能。
774 0
|
3月前
|
easyexcel Java Apache
EasyExcel导入的时候报错Caused by: java.lang.NoClassDefFoundError: org/apache/poi/poifs/filesystem/File
EasyExcel导入的时候报错Caused by: java.lang.NoClassDefFoundError: org/apache/poi/poifs/filesystem/File
285 0
|
4月前
|
Java 数据处理 开发者
Java IO流专家级教程:深入理解InputStream/OutputStream和Reader/Writer的内部机制
【6月更文挑战第26天】Java IO流涉及字节流(InputStream/OutputStream)和字符流(Reader/Writer),用于高效处理数据输入输出。InputStream/OutputStream处理二进制数据,常使用缓冲提升性能;Reader/Writer处理文本,关注字符编码转换。两者都有阻塞IO操作,但Java NIO支持非阻塞。示例代码展示了如何使用FileInputStream/FileOutputStream和FileReader/FileWriter读写文件。理解这些流的内部机制有助于优化代码性能。
108 0
|
4月前
|
Java 开发者
Java IO流实战技巧:如何优化InputStream/OutputStream和Reader/Writer的使用?
【6月更文挑战第26天】Java IO流优化涉及缓冲、资源管理、字符编码和流式处理。使用Buffered流提高读写效率,如`BufferedInputStream`和`BufferedReader`。确保资源关闭使用try-with-resources,如`try (InputStream is = ...) {...}`。处理文本时指定编码,如`InputStreamReader(is, StandardCharsets.UTF_8)`防止乱码。流式处理大文件,分块读写避免内存溢出,以减少内存占用。这些技巧能提升程序性能和健壮性。
188 0
|
4月前
|
Java
Java IO流终极指南:从InputStream/OutputStream到Reader/Writer的全面解读
【6月更文挑战第26天】Java IO流涵盖字节流(InputStream/OutputStream)和字符流(Reader/Writer),前者处理二进制数据,后者专司文本。例如,FileInputStream/FileOutputStream用于文件的字节级读写,而FileReader/FileWriter处理字符级文本。Buffered流提供缓冲功能,提升效率。选择合适的流类取决于数据类型和性能需求。
79 0
|
4月前
|
存储 设计模式 Java
Java IO流大揭秘:如何高效使用InputStream/OutputStream和Reader/Writer?
【6月更文挑战第26天】Java IO流核心基础,涉及InputStream/OutputStream(字节流)和Reader/Writer(字符流)。高效使用的关键包括:使用Buffered流提升性能,如BufferedInputStream和BufferedOutputStream;处理编码,通过InputStreamReader和OutputStreamWriter指定如UTF-8编码;应用装饰器模式,如DataOutputStream增强功能。理解并巧妙运用这些技巧能优化数据读写操作。
77 0
|
4月前
|
Java
深入探索Java IO流:InputStream/OutputStream与Reader/Writer的奥秘!
【6月更文挑战第26天】Java IO流用于输入输出操作,包括字节流(InputStream/OutputStream)和字符流(Reader/Writer)。InputStream和OutputStream处理字节数据,是所有字节流的基类,可被继承以自定义读写行为。
68 0