使用的POI包是poi-2.5.1-final-20040804.jar,用讯雷搜的。也可以到http://apache.justdn.org/jakarta/poi/下载src。加入到Java Build Path中。把Excel的内容抽取出来,输出到控制台的代码:

  1package test;
  2
  3import java.io.BufferedReader;
  4import java.io.FileInputStream;
  5import java.io.IOException;
  6import java.io.InputStream;
  7import java.io.InputStreamReader;
  8
  9import org.apache.poi.hssf.usermodel.HSSFCell;
 10import org.apache.poi.hssf.usermodel.HSSFDateUtil;
 11import org.apache.poi.hssf.usermodel.HSSFRow;
 12import org.apache.poi.hssf.usermodel.HSSFSheet;
 13import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 14
 15public class ExcelReader {
 16    //创建文件输入
 17    private BufferedReader reader = null;
 18    //文件类型
 19    private String filetype;
 20    //文件二进制输入流
 21    private InputStream is =null;
 22    //当前的Sheet
 23    private int currSheet;
 24    //当前位置
 25    private int currPosition;
 26    //Sheet数量
 27    private int numOfSheets;
 28    //HSSFWorkbook
 29    HSSFWorkbook workbook = null;
 30    //设置cell之间以空格分隔
 31    private static String EXCEL_LINE_DELIMITER = " ";
 32    //设置最大列数
 33    private static int MAX_EXCEL_COLUMNS = 64;
 34    /**
 35     * 构造函数创建一个ExcelReader
 36     * @param inputfile
 37     * @throws IOException
 38     * @throws Exception
 39     */

 40    public ExcelReader(String inputfile) throws IOException, Exception{
 41        //判断参数是否为空或者没有意义
 42        if(inputfile == null || inputfile.trim().equals("")){
 43            throw new IOException("no input file specified");
 44        }

 45        //取得文件名后缀并赋值给filetype
 46        this.filetype = inputfile.substring(inputfile.lastIndexOf(".")+1);
 47        //设置开始行为0
 48        currPosition = 0;
 49        //设置当前位置为0
 50        currSheet = 0;
 51        //创建文件输入流
 52        is = new FileInputStream(inputfile);
 53        
 54        //判断文件格式
 55        if(filetype.equalsIgnoreCase("txt")){
 56            //如果是txt则直接创建BufferedReader读取
 57            reader = new BufferedReader(new InputStreamReader(is));
 58        }
else if(filetype.equalsIgnoreCase("xls")){
 59            workbook = new HSSFWorkbook(is);
 60            //设置Sheet数
 61            numOfSheets = workbook.getNumberOfSheets();
 62        }
else{
 63            throw new Exception("File Type Not Supported");
 64        }
        
 65    }

 66    /**
 67     * 函数readLine读取文件的一行
 68     * @return
 69     * @throws IOException
 70     */

 71    public String readLine() throws IOException{
 72        //如果是txt文件则通过reader读取
 73        if(filetype.equalsIgnoreCase("txt")){
 74            String str = reader.readLine();
 75            //空行略去,直接读取下一行
 76            while(str.trim().equals("")){
 77                str = reader.readLine();                
 78            }

 79            return str;
 80        }

 81        //如果是xls文件通过POI提供的API读取文件
 82        else if(filetype.equalsIgnoreCase("xls")){
 83            //根据currSheet的值获取当前的sheet
 84            HSSFSheet sheet = workbook.getSheetAt(currSheet);
 85            //判断当前行是否到当前Sheet的结尾
 86            if(currPosition > sheet.getLastRowNum()){
 87                //当前行位置清零
 88                currPosition = 0;
 89                //判断是否还有Sheet
 90                while(++currSheet < numOfSheets){
 91                    //得到下一张sheet
 92                    sheet = workbook.getSheetAt(currSheet);
 93                    
 94                    //当前行数是否已达到文件末尾
 95                    if(currPosition == sheet.getLastRowNum()){
 96                        continue;
 97                    }
else{
 98                        //获取当前行数
 99                        int row = currPosition;
100                        currPosition++;
101                        //读取当前行数据
102                        return getLine(sheet,row);
103                    }

104                }

105                return null;
106            }

107            //获取当前行数
108            int row = currPosition;
109            currPosition++;
110            //读取当前行数据
111            return getLine(sheet,row);
112        }

113        return null;        
114    }

115    
116    /**
117     * 函数getLine返回Sheet的一行数据
118     * @param sheet
119     * @param row
120     * @return
121     */

122    private String getLine(HSSFSheet sheet, int row){
123        //根据行数取得Sheet的一行
124        HSSFRow rowline = sheet.getRow(row);
125        //创建字符串缓冲区
126        StringBuffer buffer = new StringBuffer();
127        //获取当前行的列数
128        int fieldColumns = rowline.getLastCellNum();
129        HSSFCell cell = null;
130        //遍历所有列
131        for(int i=0;i<fieldColumns;i++){
132            //取得当前Cell
133            cell = rowline.getCell((short)i);
134            String cellvalue = null;
135            if(cell != null){
136                switch(cell.getCellType()){
137                case HSSFCell.CELL_TYPE_NUMERIC:{
138                    //判断当前的Cell的Type是否为Date
139                    if(HSSFDateUtil.isCellDateFormatted(cell)){
140                        //如果是Date类型,取得该Cell的Date值
141                        cellvalue = cell.getDateCellValue().toString();
142                    }
else {//如果是纯数字
143                        Integer num = new Integer((int)cell.getNumericCellValue());
144                        cellvalue = String.valueOf(num);
145                    }

146                    break;
147                }

148                //如果当前Cell的Type为String
149                case HSSFCell.CELL_TYPE_STRING:
150                    //取得当前Cell的字符串
151                    cellvalue = cell.getStringCellValue().replaceAll("'""''");
152                    break;
153                //默认的Cell值
154                default:
155                    cellvalue = "";
156                }

157            }
else{
158                cellvalue = "";
159            }

160            //在每个字段之间插入分隔符
161            buffer.append(cellvalue).append(EXCEL_LINE_DELIMITER);
162        }

163        return buffer.toString();
164    }

165    
166    /**
167     * close函数执行流的关闭操作
168     */

169    public void close(){
170        //如果is不为空,则关闭InputStream文件输入流
171        if(is != null){
172            try{
173                is.close();
174            }
catch(IOException e){
175                is = null;
176            }

177            //如果Reader不为空,则关闭BufferedReader文件输入流
178            if(reader != null){
179                try{
180                    reader.close();
181                }
catch(IOException e){
182                    reader = null;
183                }
                
184            }

185        }

186    }

187    /**
188     * @param args
189     */

190    public static void main(String[] args) {
191        // TODO Auto-generated method stub
192        try {
193            ExcelReader er = new ExcelReader("d:\\index\\names.xls");
194            String line = er.readLine();
195            while(line != null){
196                System.out.println(line);
197                line = er.readLine();
198            }

199            er.close();
200        }
 catch (Exception e) {
201            // TODO Auto-generated catch block
202            e.printStackTrace();
203        }

204        
205    }

206}

207
posted on 2009-01-20 16:27  何婧  阅读(1185)  评论(0编辑  收藏  举报