- 必须同步提交form表单
- Form表单编码方式 multipart/form-data
- 提交方式必须为post
- 上传文件对应 input type=”file” 元素要提供name属性
$("#button-import").upload({
action : '../../area_batchImport.action',
// 在选择文件的时候触发的事件
onSelect :function(){
// 选中文件后,关闭自动提交
this.autoSubmit = false ;
// 判定文件格式 ,以.xls 或者 .xlsx 结尾
var filename = this.filename();
var regex = /^.*\.(xls|xlsx)$/ ;
if(regex.test(filename)){
// 满足
this.submit();
}else{
//不满足
$.messager.alert("警告","只能上传.xls或.xlsx结尾的文件!","warning");
}
},
onComplete : function(response){
$.messager.alert("成功","文件上传成功!","info");
}
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>${poi.version}</version>
@Action(value = "area_importArea")
public String importArea() throws IOException {
// 编写解析代码逻辑
// 基于.xls 格式解析 HSSF
// 1、 加载Excel文件对象
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
// 2、 读取一个sheet
HSSFSheet sheet = hssfWorkbook.getSheetAt(0);//获取第一个sheet对象
// 3、 读取sheet中每一行,一行数据 对应 一个区域对象
for (Row row : sheet) {
// 第一行表头跳过
if (row.getRowNum() == 0) {
// 第一行 跳过
continue;
}
// 跳过空值的行,要求此行作废
if (row.getCell(0) == null
|| StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
continue;
}
Area area = new Area();
area.setId(row.getCell(0).getStringCellValue());//区域编号
area.setProvince(row.getCell(1).getStringCellValue());//省份
area.setCity(row.getCell(2).getStringCellValue());//城市
area.setDistrict(row.getCell(3).getStringCellValue());//区域
area.setPostcode(row.getCell(4).getStringCellValue());//邮编
areas.add(area);
}
// 调用业务层
areaService.saveAreas(areas);
return NONE;