首先导入poi的包
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
<!-- 图表生成 需要的poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
代码如下:
// 读取excel数据
private static void excelFileRead() throws IOException {
FileInputStream xlsStream = null;
try {
// Excel工作簿 输入流
xlsStream = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\aa.xls"));
// 构造工作簿对象
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(xlsStream);
// hssfWorkbook.getNumberOfSheets()//获取excel表当中的sheet总数
HSSFSheet sheetAt = hssfWorkbook.getSheetAt(0);//获取第一个sheet页面
int firstRowNum = sheetAt.getFirstRowNum();//获取第一行的下标
int lastRowNum = sheetAt.getLastRowNum();//获取最后一行的下标
for (int i=firstRowNum;i<=lastRowNum;i++){//循环其中的数据
// 获取行,行号作为参数传递给getRow方法
HSSFRow row = sheetAt.getRow(i);
// 获取单元格,row已经确定了行号,列号作为参数传递给getCell,就可以获得相应的单元格了
String code = row.getCell(0).getStringCellValue();
String title = row.getCell(1).getStringCellValue();
String contentSummary = row.getCell(3).getStringCellValue();
System.out.println("获取到的第一列是:" + code +" 获取到的第二列是:" + title + " 获取到的第三列是:" + contentSummary);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (xlsStream != null) {
try {
xlsStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}