View Javadoc

1   /*
2    * Copyright 2004-2006 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.seasar.tuigwaa.database.util;
17  
18  import java.io.IOException;
19  import java.io.InputStream;
20  
21  import org.apache.poi.hssf.usermodel.HSSFCell;
22  import org.apache.poi.hssf.usermodel.HSSFRow;
23  import org.apache.poi.hssf.usermodel.HSSFSheet;
24  import org.apache.poi.hssf.usermodel.HSSFWorkbook;
25  import org.apache.poi.poifs.filesystem.POIFSFileSystem;
26  
27  /***
28   * @author someda
29   */
30  public class ExcelfileLoader extends DatafileLoader {
31  
32  	private POIFSFileSystem fs;
33  	private HSSFWorkbook wb;
34  	private HSSFSheet sheet;
35  	
36  	private int firstRowNum;
37  	private int currentLineNum;
38  	private int lastRowNum;	
39  	
40  	public ExcelfileLoader(InputStream inputStream){
41  		super(inputStream);		
42  		try{
43  			fs = new POIFSFileSystem(inputStream);
44  			wb = new HSSFWorkbook(fs);
45  			sheet = wb.getSheetAt(0);
46  			firstRowNum = sheet.getFirstRowNum();
47  			lastRowNum = sheet.getLastRowNum();
48  			currentLineNum = firstRowNum - 1;
49  		}catch(IOException ioe){		
50  		}		
51  	}
52  	
53  	public String[] load() {
54  
55  		if(hasNext()){
56  			HSSFRow row = sheet.getRow(currentLineNum);
57  			int firstCell = row.getFirstCellNum();
58  			int lastCell = row.getLastCellNum();									
59  			String[] data = new String[lastCell-firstCell];
60  			for(int j=firstCell;j<lastCell;j++){
61  				HSSFCell cell = row.getCell((short)j);				
62  				switch(cell.getCellType()){
63  					case HSSFCell.CELL_TYPE_NUMERIC:
64  						data[j-firstCell]=numToString(cell.getNumericCellValue());
65  						break;
66  					case HSSFCell.CELL_TYPE_STRING:
67  						data[j-firstCell]=cell.getStringCellValue();
68  						break;
69  					default:
70  						data[j-firstCell]=null;
71  						break;
72  				}				
73  			}			
74  			return data;
75  		}		
76  		return null;
77  	}
78  	
79  	
80  	private boolean hasNext(){
81  		boolean hasNext = false;		
82  		if(currentLineNum < lastRowNum){
83  			hasNext = true;
84  			currentLineNum++;
85  		}
86  		return hasNext;
87  	}
88  	
89  	private String numToString(double num){
90  		String numString = num + "";
91  		return numString.replaceAll(".0$","");
92  	}	
93  
94  }