Java使用Apache POI操作excel文件

发表于:2014-9-01 10:54

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:布加迪    来源:51cto

  读取excel文件的内容:
public static void readExcel() throws InvalidFormatException, IOException {
// Use a file
Workbook wb1 = WorkbookFactory.create(new File("e:/test/userinfo.xls"));
Sheet sheet = wb1.getSheetAt(0);
// Decide which rows to process
// int rowStart = Math.min(10, sheet.getFirstRowNum());
// int rowEnd = Math.max(40, sheet.getLastRowNum());
int rowStart = sheet.getLastRowNum();
int rowEnd = sheet.getLastRowNum() + 1;
logger.info(sheet.getFirstRowNum());
logger.info(sheet.getLastRowNum());
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
Row r = sheet.getRow(rowNum);
int lastColumn = Math.max(r.getLastCellNum(), 10);
logger.info(lastColumn);
// To get the contents of a cell, you first need to know what kind
// of cell it is (asking a string cell for its numeric contents will
// get you a NumberFormatException for example). So, you will want
// to switch on the cell's type, and then call the appropriate
// getter for that cell.
for (int cn = 0; cn < lastColumn; cn++) {
// Cell cell = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
Cell cell = r.getCell(cn);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
logger.info(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
logger.info(cell.getDateCellValue());
} else {
logger.info(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
logger.info(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
logger.info(cell.getCellFormula());
break;
default:
logger.info("empty");
}
}
}
}
  下面给出一个具体的例子,实例中的excel文件内容如下:
32/3<123>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号