日期:2014-05-16  浏览次数:21123 次

用apache poi 读取excel文件很方便
用三个循环遍历就行了: 第一层是sheet循环,然后是行循环,最后是单元格循环.

package com.jie.java;

import java.io.File;
import java.io.FileInputStream;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelRead {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		try{
			FileInputStream is = new FileInputStream(new File("c:/最终成绩.xls"));
			HSSFWorkbook wb=new HSSFWorkbook(is);
			
			int sheetNum=wb.getNumberOfSheets();
			
			for(int i=0;i<sheetNum;i++)
			{
				HSSFSheet childSheet = wb.getSheetAt(i);
				int rowNum = childSheet.getLastRowNum();
				
				for(int j=0;j<rowNum;j++)
				{
				    HSSFRow row = childSheet.getRow(j);	
				    int cellNum=row.getLastCellNum();
				    
				    for(int k=0;k<cellNum;k++)
				    {
				    	System.out.print(row.getCell(k).toString()+" ");
				    }
				    System.out.println();
				}
				
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}

	}

}
1 楼 yaoneng 2010-04-25  
谢谢楼主,弄明白了~~
2 楼 cuisuqiang 2010-09-09  
楼主是否发现int sheetNum=wb.getNumberOfSheets();在读取时,如果各行有数据,就读取不到了!
3 楼 mady0505 2011-03-22  
楼下的童鞋,如果有隔行,稍微判断一下就可以了
if(row!=null){
	int cellNum = row.getLastCellNum();
	System.out.println("cellNum--"+cellNum);
	for(int j=0; j<cellNum; j++){
	     HSSFCell cell = row.getCell(j);
	     if(cell!=null){
	     System.out.println("sheet "+m+" row "+i+" column "+j+":  "+ cell);
	     }
        }
}
4 楼 akushin 2011-06-03  
是不是会少一行··