1.文件上传机制采用struts2,来接收上传的文件
private File file; public void setFile(File file) { this.file = file; }
x
1
private File file;
2
3
public void setFile(File file) {
4
this.file = file;
5
}
2.实现Excel文件解析
jar包导入(这种jar包导入基于maven项目管理)
org.apache.poi poi 3.11 org.apache.poi poi-ooxml 3.11 org.apache.poi poi-ooxml-schemas 3.11
x
1
2
3
org.apache.poi
4
poi
5
3.11
6
7
8
org.apache.poi
9
poi-ooxml
10
3.11
11
12
13
org.apache.poi
14
poi-ooxml-schemas
15
3.11
16
表格里数据的格式:
![]() |
代码实现表格数据解析
public void resolveExcel() { //1.加载excal文件对象 Workbook workbook=null; try { workbook = WorkbookFactory.create(new FileInputStream(file)); } catch (Exception e) { e.printStackTrace(); } //2.读取第一个sheet Sheet sheet = workbook.getSheetAt(0); //3.读取sheet中的每一行 for (Row row : sheet) { //跳过第一行表头数据(如果有表头就跳过,没有则不用) if (row.getRowNum()==0) { continue; } //跳过空行 if (row.getCell(0)==null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) { continue; } //分别获取每一列的数据 String areaCode = row.getCell(0).getStringCellValue(); String province = row.getCell(1).getStringCellValue(); String city = row.getCell(2).getStringCellValue(); String area = row.getCell(3).getStringCellValue(); String postcode = row.getCell(4).getStringCellValue(); //接下来要对得到的数据怎么操作,随业务而定了!可以先打印测试一下 } }
30
1
public void resolveExcel() {
2
//1.加载excal文件对象
3
Workbook workbook=null;
4
try {
5
workbook = WorkbookFactory.create(new FileInputStream(file));
6
} catch (Exception e) {
7
e.printStackTrace();
8
}
9
//2.读取第一个sheet
10
Sheet sheet = workbook.getSheetAt(0);
11
//3.读取sheet中的每一行
12
for (Row row : sheet) {
13
//跳过第一行表头数据(如果有表头就跳过,没有则不用)
14
if (row.getRowNum()==0) {
15
continue;
16
}
17
//跳过空行
18
if (row.getCell(0)==null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
19
continue;
20
}
21
//分别获取每一列的数据
22
String areaCode = row.getCell(0).getStringCellValue();
23
String province = row.getCell(1).getStringCellValue();
24
String city = row.getCell(2).getStringCellValue();
25
String area = row.getCell(3).getStringCellValue();
26
String postcode = row.getCell(4).getStringCellValue();
27
28
//接下来要对得到的数据怎么操作,随业务而定了!可以先打印测试一下
29
}
30
}