一键上传功能
环境搭建
<!-- 导入jquery核心类库 -->
<script type="text/javascript" src="../../js/jquery-1.8.3.js"></script>
<!-- 导入ocupload -->
<script type="text/javascript" src="../../js/ocupload/jquery.ocupload-1.1.2.js" ></script>
代码范例
jsp代码:
方法:
//文件上传后触发的事件 : //文件上传后触发的事件 onComplete:function () {
alert("文件上传成功"); }
//绑定一键上传按钮
$("#button-import").upload({
action:"${pageContext.request.contextPath}/bcRegion/importExecl.action",//文件上传的地址
name:"excelFile", //文件上传的名称
onComplete:function () {
alert("文件上传成功");
$('#grid').datagrid('reload');
}
});
});
Controller:后端代码
//导入设置
@RequestMapping(value = "importExecl.action",method = RequestMethod.POST)
@ResponseBody
public String importExecl(MultipartFile excelFile) throws IOException {
ArrayList<BcRegion> bcRegions = new ArrayList<>();//创建一个集合
try {
HSSFWorkbook workbook = new HSSFWorkbook(excelFile.getInputStream());//创建一个工作集
HSSFSheet sheet = workbook.getSheetAt(0);//创建一个sheet
int lastRowNum = sheet.getLastRowNum();//获得最后一行
for (int i=1;i<lastRowNum;i++){//遍历循环
HSSFRow row = sheet.getRow(i); //得到每一行的数据
BcRegion bcRegion = new BcRegion();
bcRegion.setId(UUID32Gen.gen32UUIDString()); //设置id为UUID32Gen.gen32UUIDString类型
//根据行数创建列
short cellNum = row.getLastCellNum();
for (int j=0;j<lastRowNum;j++){ //内循环
switch (j){
case 1:
bcRegion.setProvince(row.getCell(j).getStringCellValue());//省
break;
case 2:
bcRegion.setCity(row.getCell(j).getStringCellValue());//市
break;
case 3:
bcRegion.setDistrict(row.getCell(j).getStringCellValue());//区
break;
case 4:
bcRegion.setPostcode(row.getCell(j).getStringCellValue());//邮编
break;
}
// bcRegions.add(bcRegion);
}
//设置城市编码和简码
String province=bcRegion.getProvince();
String city=bcRegion.getCity();
String district=bcRegion.getDistrict();
//例如:Sting province="菏泽市" 将市截取,剩菏泽
province=province.substring(0,province.length()-1);
city=city.substring(0,city.length()-1);
district=district.substring(0,district.length()-1);
bcRegion.setCitycode(PinyinHelper.convertToPinyinString(province,"", PinyinFormat.WITHOUT_TONE));//获取城市编码
bcRegion.setShortcode(PinyinHelper.getShortPinyin(province+city+district));//获取简码
bcRegions.add(bcRegion);
}
//保存到数据库
this.bcRegionServiceI.saveAll(bcRegions);
} catch (Exception e) {
e.printStackTrace();
}
return "base/region";
}
- //保存到数据库
this.bcRegionServiceI.saveAll(bcRegions); | |
---|---|
//导入接口 |
@Override
@Transactional
public void saveAll(List<BcRegion> list) {
for (BcRegion bcRegion:list){
this.bcRegionMapper.insertSelective(bcRegion);
}
} | |
运行效果
JPinYin插件
String province = "山西省";
String city = "太原市";
String district = "清徐县";
province=province.substring(0,province.length()-1);
city=city.substring(0,city.length()-1);
district=district.substring(0,district.length()-1);
System.out.println(province);
System.out.println(city);
System.out.println(district);
System.out.println(PinyinHelper.convertToPinyinString(city,"", PinyinFormat.WITHOUT_TONE));//城市简码 taiyuan
System.out.println(PinyinHelper.getShortPinyin(province+city+district));//简码 sxtyqx