您的位置:首页 > 编程语言

jxl解析excel表格代码

2017-02-04 16:31 183 查看

jxl解析excel表格代码

/**
* @author Yuansheng.Lei
* excel表格导入工具类
*/
public class Excel {

/**
* 提取excel表信息
* @param filePath
* @return
* @throws IOException
*/
public static List<Dto> getData(String filePath){

//构造excel文件输入流对象
InputStream is = null;
Workbook workbook = null;
List<Dto> list = null;
try {
is = new FileInputStream(filePath);
//创建工作簿对象
workbook = Workbook.getWorkbook(is);
//获取工作簿的个数,对应于一个excel中的工作表个数
workbook.getNumberOfSheets();
//使用索引获取第一个工作表,也可以使用 workbook.getSheet(sheetName),其中sheetName表示工作表的名称
Sheet sheet = workbook.getSheet(0);

int rows = sheet.getRows(); //获取工作表的总行数
int columns = sheet.getColumns();//获取工作表的总列数

list = new ArrayList<Dto>();
for (int i = 1; i < rows; i++) {
Dto dto = Dtos.newDto();
for (int j = 0; j < columns; j++) {
//注意:这里的getCell方法的参数,第一个指定第几列,第二个参数才是指第几行
Cell cell = sheet.getCell(j, i);
if(cell.getType() == CellType.DATE){
DateCell dateCell = (DateCell) cell;
dto.put("a"+(j+1),AOSUtils.date2String(dateCell.getDate(), "yyyy-MM-dd") );
}else{
dto.put("a"+(j+1), cell.getContents());
}
}
list.add(dto);
}
} catch (FileNotFoundException e) {
throw new AOSException("未找到该路径下的文件",e);
// e.printStackTrace();
} catch (BiffException e) {
throw new AOSException("工作簿对象创建不成功",e);
// e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if (workbook != null) {
workbook.close();//关闭工作空间
}
if (is != null) {
try {
is.close();//关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: