java原生读取excel文件非常的麻烦,不过Apache为我们提供了一个非常好用的工具:POI,它可以处理Office的各类文件,例如word、excel等等。现在我们来进行处理吧!
首先我们要导入需要的依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
代码实现:
public static void main(String[] args) throws IOException, InvalidFormatException {
//读取文件
File in= new File("C:\\Users\\QianSheng\\Desktop\\is.xlsx");
//获取工作簿
XSSFWorkbook sheets = new XSSFWorkbook(in);
//获取第0个工作表
XSSFSheet sheet = sheets.getSheetAt(0);
//获取行
for (Row rows : sheet) {
//获取单元格
for (Cell cell : rows) {
//设置要读取的单元格的类型
cell.setCellType(CellType.STRING);
String s = cell.getStringCellValue();
System.out.print(s+" ");
}
System.out.println();
}
}
为了方便展示我就把异常都在主方法里面抛出了,各位在写的时候可以处理一下。
让我们一起来看看结果吧!
excel文件内容:
代码读取结果:
注意:只能处理2003版本以上的后缀为.xlsx的文件,如处理.XLS文件,需要把代码中的XSSF该为HSSF!