使用Java读取Excel文件的内容非常简单,Apache POI这个项目已经实现了对此类文档操作的功能,我们只需学会如何使用它即可。
1.首先需要引入Apache POI,这里推荐使用Maven的方式管理项目依赖。在pom.xml文件中加入依赖项:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
2.假设现有如下Excel(.xlsx格式),需要读取红色框内的内容。
![一份Excel格式的课程安排表](https://img-blog.csdn.net/20170702164102303?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMjMyNTE2Nw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
3.开撸代码
private static void parseInfoFromInputFile(String inputFilePath, int rowBegin) throws IOException {
FileInputStream fileInput = new FileInputStream(inputFilePath);
XSSFWorkbook wb = new XSSFWorkbook(fileInput);
XSSFSheet sheet = wb.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
for (int i = rowBegin; i <= lastRowNum; ++i) {
XSSFRow row = sheet.getRow(i);
int columnNum = row.getLastCellNum();
for (int j=0; j<columnNum; ++j) {
XSSFCell cell = row.getCell(j);
if (j == 0) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
System.out.printf("%s\t", format.format(cell.getDateCellValue()));
} else if (CellType.NUMERIC.equals(cell.getCellTypeEnum())) {
System.out.printf("%.0f\t", cell.getNumericCellValue());
} else {
System.out.printf("%s\t", cell.getStringCellValue());
}
}
System.out.println();
}
wb.close();
fileInput.close();
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
4.得到输出结果:
2017-07-02 4:00-6:00 听说 2 宋润宁
2017-07-03 1:30-3:30 读写 2 张颖
2017-07-04 4:00-6:00 读写 2 张颖
2017-07-05 7:00-9:00 听说 2 宋润宁
2017-07-06 4:00-6:00 听说 2 宋润宁
2017-07-07 7:00-9:00 读写 2 张颖
2017-07-08 8:30-10:30 听说 2 宋润宁
2017-07-09 8:30-10:30 读写 2 张颖
2017-07-10 4:00-6:00 读写 2 张颖
2017-07-11 4:00-6:00 听说 2 宋润宁
2017-07-12 2:00-4:00 读写 2 张颖
2017-07-21 5:00-7:00 听说 2 宋润宁
2017-07-22 4:00-6:00 读写 2 张颖
2017-07-23 4:00-6:00 听说 2 宋润宁
2017-07-24 4:00-6:00 听说 2 宋润宁
2017-07-25 10:30-12:30 读写 2 张颖
2017-07-26 8:30-10:30 读写 2 张颖
2017-07-29 4:00-6:00 听说 2 宋润宁
2017-07-30 8:30-10:30 听说 2 宋润宁
2017-07-31 4:00-6:00 听说 2 宋润宁
2017-07-31 7:00-9:00 读写 2 张颖
2017-08-01 7:00-9:00 听说 2 宋润宁
2017-08-02 8:30-10:30 读写 2 张颖
2017-08-02 2:00-4:00 听说 2 宋润宁
2017-08-04 10:30-12:30 读写 2 张颖
2017-08-05 4:00-6:00 读写 2 张颖
2017-08-06 10:30-12:30 读写 2 张颖
...略...