Java讀取EXCAL

package cn.com.nuoter.playbar.sendWinMessages.action;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ReadRepairInfo {
private String filePath = null; //Excel文件的存放全路徑

/*控制格式的變量*/
private int headNum = 1; //控制從第headNum行開始讀取,因爲行的索引是從0開始的

ReadRepairInfo(String file){
this.filePath=file;
}


/**
*
* TODO 從Excel文件中讀取維護信息,並添加到RepairInfoBean中去
*
*/
@SuppressWarnings({ "unchecked", "deprecation" })
public ArrayList readExcel4RepairInfo(){
ArrayList table= new ArrayList();
ArrayList record= new ArrayList();
try {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(filePath));
HSSFSheet sheet = workbook.getSheetAt(0); //得到一個Sheet
/*獲得導入的記錄數,也就是數據的行數*/
int rowNum = sheet.getLastRowNum()-headNum; //行的索引是從0開始的
/*遍歷所有數據,並將得到的數據傳給rInfo*/
for(int i= headNum;i<= rowNum;i++){
HSSFRow row = sheet.getRow(i);
for(short j = row.getFirstCellNum();j<row.getLastCellNum();j++){
String cellContent1 = null;
HSSFCell cell = row.getCell(j);
cellContent1 = cell.getStringCellValue();
record.add(cellContent1);
}
table.add(getRepairInfoBean(record));
//新建數組,否則是同一條記錄
record = new ArrayList();
}
} catch (FileNotFoundException e) {
System.out.println("找不到文件 " + filePath);
e.printStackTrace();
} catch (IOException e) {
System.out.println("訪問文件出錯 " + filePath);
e.printStackTrace();
}
return table;
}

/**
*
*
* TODO 用從Excel讀取的記錄生成RepairInfoBean
*
* @param ArrayList 從Excel讀取的一條記錄,即一行
*/
public RepairInfoBean getRepairInfoBean(ArrayList content){

RepairInfoBean rpInfo = new RepairInfoBean();
if(content!=null&&!(content.isEmpty())){
/*給RepairInfoBean的對象傳入數據*/
rpInfo.setSt1(content.get(0).toString());
rpInfo.setSt2(content.get(1).toString());
rpInfo.setSt3(content.get(2).toString());
rpInfo.setSt4(content.get(3).toString());
rpInfo.setSt5(content.get(4).toString());
rpInfo.setSt6(content.get(5).toString());
}
return rpInfo;
}


/*測試函數*/
@SuppressWarnings("unchecked")
public static void main(String[] args){
ReadRepairInfo readRepairInfo = new ReadRepairInfo("F:\\tr.xls");
ArrayList list = readRepairInfo.readExcel4RepairInfo();
Iterator it=list.iterator();
while(it.hasNext()){
RepairInfoBean rpInfo = (RepairInfoBean)it.next();
System.out.println("第一列"+rpInfo.getSt1());
}
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章