springboot使用poi读取excel文件
Easul Lv6

引入的jar包

折叠代码块XML 复制代码
1
2
3
4
5
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>

基本调用代码

折叠代码块JAVA 复制代码
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.jd.jrmserver.base.test;

import org.apache.poi.hssf.usermodel.*;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
* 读取上篇中的xls文件的内容,并打印出来
*
* @author Administrator
*/
public class ExcelTest {

/**
* 读取一个excel文件的内容
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//extractor();
readTable();
}


//通过对单元格遍历的形式来获取信息 ,这里要判断单元格的类型才可以取出值
public static void readTable() throws Exception {
InputStream ips = new FileInputStream("C:\\Users\\liubin52\\Desktop\\test.xls");
HSSFWorkbook wb = new HSSFWorkbook(ips);
HSSFSheet sheet = wb.getSheetAt(0);
for (Iterator ite = sheet.rowIterator(); ite.hasNext(); ) {
HSSFRow row = (HSSFRow) ite.next();
System.out.println();
for (Iterator itet = row.cellIterator(); itet.hasNext(); ) {
HSSFCell cell = (HSSFCell) itet.next();
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_BOOLEAN:
//得到Boolean对象的方法
System.out.print(cell.getBooleanCellValue() + " ");
break;
case HSSFCell.CELL_TYPE_NUMERIC:
//先看是否是日期格式
if (HSSFDateUtil.isCellDateFormatted(cell)) {
//读取日期格式
System.out.print(cell.getDateCellValue() + " ");
} else {
//读取数字
System.out.print(cell.getNumericCellValue() + " ");
}
break;
case HSSFCell.CELL_TYPE_FORMULA:
//读取公式
System.out.print(cell.getCellFormula() + " ");
break;
case HSSFCell.CELL_TYPE_STRING:
//读取String
System.out.print(cell.getRichStringCellValue().toString() + " ");
break;
}
}
}
}

}

如果代码老是报错,那么把xls重新保存一下可能会解决问题
不是xls的文件可以另存为xls的文件

参考

 评论
来发评论吧~
Powered By Valine
v1.5.2