Java读取Excel示例

     
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

/**
* @param filePath excel文件路径
* @param col 有效记录列数
* @return 表格内容(每个单元格内容均为String类型)
*/
public static List<List<String>> initExcle(String filePath, int col) {
// className = Helper.upperFirst(f.getName()).split(".xls")[0];
File f = new File(filePath);
List<List<String>> list = null;
InputStream is = null;
HSSFWorkbook wb = null;
try {
is = new FileInputStream(f);
wb = new HSSFWorkbook(is);
} catch (Exception e) {
Helper.logException("Cannot find file or file cannot be reading!",
e.fillInStackTrace());
} finally {
try {
is.close();
} catch (IOException e) {
Helper.logException("Cannot close input stream!",
e.fillInStackTrace());
}
}
// deal work book.
if (null != wb) {
list = new ArrayList<List<String>>();
Sheet sheet = wb.getSheetAt(wb.getFirstVisibleTab());
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
List<String> args = new ArrayList<String>();
Row row = sheet.getRow(i);
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell c = row.getCell(j);
if (null != c) {
if (c.getCellType() == 0) {
args.add(c.getNumericCellValue() + "");
} else if (c.getRichStringCellValue().toString().trim()
.equals("")) {
continue;
} else {
args.add(c.getRichStringCellValue().toString()
.trim());
}
}
}
if (args.size() != col)
continue;
list.add(args);
}
} else {
Helper.logError("Excel file has nothing!");
}
return list;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值