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());
}
}
}

你可能感兴趣的:(java,职场,休闲)