相比Excel导出,导入略为麻烦点,没关系,认真看代码就好
1.页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<@sp.themes/>
<#if sucMsg?exists>
<script>
$(function(){
$.lt.alert('导入成功!',{title:'提示信息',t:'info',close:function(){
parent.win.dialog("close");
parent.location.reload();
}});
});
</script>
</#if>
<script>
function back(){
parent.win.dialog("close");
}
function sub(){
var kds = $("#excelFile").val();
if(kds == ""){
$.lt.alert('未选择文件!',{title:'提示信息',t:'info'});
}else{
var jd = kds.lastIndexOf(".");
var fks = kds.substring(jd);
if(fks == ".xlsx" || fks == ".xls"){
$("#fileUpload").submit();
}else{
$.lt.alert('文件错误,请选择 .xlsx 或 .xls 类表格!',{title:'提示信息',t:'info'});
}
}
}
function downloadModalExcel()
{
window.open("${rc.contextPath}/excelTemp/zydmxx.xlsx", "_self");
}
</script>
</head>
<body>
<div class="mod_box no_mar">
<form id="fileUpload" action="${rc.contextPath}/bg/dmgl/importZyExcelSubmit.html" enctype="multipart/form-data" method="post">
<table class="table txtC" style="width: 100%">
<tr >
<td> <input id="excelFile" name="excelFile" type="file"/> </td>
</tr>
<tr >
<td align="left" style="padding-left: 30%">
注意:<br>
1:专业代码信息模板下载 :<a style="color: blue;" href='javascript:void(0);' title="点击下载模板" onclick="downloadModalExcel();">点击下载模板</a><br>
2:批量导入数据只接受xlsx或xls的数据。 <br>
3:请确保使用正确模板数据,以免导入失败。<br>
</td>
</tr>
<tr>
<td>
<input type="button" class="btn btnA" onclick="sub()" value="提交" />
<input type="button" class="btn btnA" onclick="back()" value="取消" />
</td>
</tr>
</table>
<#if errMsg?exists>
<div style="padding-left: 25%">
<h6 >错误信息:</h6>
<div style="color: red;padding-left: 20px;">
<#if errMsg?exists>${errMsg}</#if>
</div>
</div>
</#if>
</form>
</div>
</body>
</html>
2.controller层:代码略多,仔细看,慢慢看
/**
* 专业代码导入--提交
* @Description TODO
* @param request
* @param response
* @return
* @throws IOException
* @throws InvalidFormatException
* @throws ParseException
* @author XuJD
* @date 2017-3-29
*/
public ModelAndView importZyExcelSubmit(HttpServletRequest request,
HttpServletResponse response)throws IOException, InvalidFormatException, ParseException {
Map<String,Object> modelMap = new HashMap<String,Object>();
ResponseDto rDto=uploadFileAction(request.getSession(),request, response);
if(rDto.isResultBool()){
modelMap.put("sucMsg", "succes");
}else{
modelMap.put("errMsg", rDto.getErrMsg());
}
modelMap.put("resModel", new YxXsxxJxxf());
return new ModelAndView(importZyExcelView).addAllObjects(modelMap);
}
rivate ResponseDto uploadFileAction(HttpSession session,
HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException, InvalidFormatException {
ResponseDto rDto = new ResponseDto();
try{
String data="";
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 获取文件
MultipartFile file = multipartRequest.getFile("excelFile");
// 设置返回类型, 字符集 ,防止乱码
response.setContentType("text/html; charset=utf-8");
//获取服务器路径
String path = session.getServletContext().getRealPath("/");
//文件保存路径
File filePath = new File(path + "ImportZyExcel");
// 如果文件夹不存在则创建
if (!filePath.exists()) {
filePath.mkdirs();
}
// 获取系统文件名,系统文件名由当前时间的值加上3位随机生成吗构成 file.getOriginalFilename():文件原名称
String systemFileName = new Long(System.currentTimeMillis()).toString() + new Random().nextInt() % 1000;
FileOutputStream io = null;
try {
io = new FileOutputStream(filePath+"/"+ systemFileName + file.getOriginalFilename());
io.write(file.getBytes());
io.close();
} catch (Exception e) {
rDto.setErrMsg("导入失败");
rDto.setResultBool(false);
return rDto;
} finally {
response.getWriter().write(data);
response.getWriter().flush();
}
//从服务器读取文件,并写入数据库
//获取文件路径
String fullPath = filePath+"/" + systemFileName + file.getOriginalFilename();
//解析excel
Workbook wookbook = null;
wookbook = WorkbookFactory.create(new FileInputStream(fullPath));
Sheet sheet = wookbook.getSheetAt(0);//统计excel的行数
int rowLen = sheet.getPhysicalNumberOfRows();//excel总行数,记录数=行数-1,第一行为标题栏,后面才是我们要拿的数据
List<OmZy> exlList = new ArrayList<OmZy>();
OmZy omZy;
OmXy omXy = new OmXy();
//院系
List<YxCommon> xyList = commonAppService.getXyList(null);
//专业
List<YxCommon> zyList = commonAppService.getZyList(omXy);
//批次
List<YxCommon> pcList = commonAppService.getPcList(null);
StringBuffer errors = new StringBuffer();
Boolean flag = false;
if(rowLen<=1){
errors.append("模版中无数据!").append("<br>");
}else{
for(int i=1;i<rowLen;i++){//把Excel表中数据放入exlList(integers);
omZy = new OmZy();
Row row = sheet.getRow(i);
int startCol = 0;
if (row != null) {
//将Excel中各行记录依次导入到yxXsxxJxxf的list中
String pcId = getValue(row.getCell(startCol++));//批次号
String zydm = getValue(row.getCell(startCol++));//专业代码
String zymc = getValue(row.getCell(startCol++));//专业名称
String zyjc = getValue(row.getCell(startCol++));//专业简称
String xydm = getValue(row.getCell(startCol++));//学院代码
String sfqy = getValue(row.getCell(startCol++));//是否启用
//判断批次ID是否存在
if(pcId==null||"".equals(pcId)){
errors.append("第"+(i+1)+"行的批次ID不能为空").append("<br>");
}else{
for(int j=0;j<pcList.size();j++){
if((String.valueOf(pcList.get(j).getKey())).equals(pcId)){
flag = true;
}
}
if(!flag){
errors.append("第"+(i+1)+"行的批次不存在").append("<br>");
}else{
flag=false;
}
}
//判断学院代码是否存在
if(xydm==null||"".equals(xydm)){
errors.append("第"+(i+1)+"行的学院代码不能为空").append("<br>");
}else{
for(int j=0;j<xyList.size();j++){
if((String.valueOf(xyList.get(j).getKey())).equals(xydm)){
flag = true;
}
}
if(!flag){
errors.append("第"+(i+1)+"行的学院代码不存在").append("<br>");
}else{
flag=false;
}
}
//判断专业代码是否已经存在
if(zydm==null||"".equals(zydm)){
errors.append("第"+(i+1)+"行的专业代码不能为空").append("<br>");
}else{
for(int j=0;j<zyList.size();j++){
if((String.valueOf(zyList.get(j).getKey())).equals(zydm)){
flag = true;
}
}
if(flag){
errors.append("第"+(i+1)+"行的专业代码已经存在").append("<br>");
}else{
flag=false;
}
}
//判断学院名称是否为空
if(zymc==null||"".equals(zymc)){
errors.append("第"+(i+1)+"行的专业名称不能为空").append("<br>");
}
//判断学院类型是否为空
if(zyjc==null||"".equals(zyjc)){
errors.append("第"+(i+1)+"行的专业简称不能为空").append("<br>");
}
//判断是否启用为空
if(sfqy==null||"".equals(sfqy)){
errors.append("第"+(i+1)+"行的是否启用不能为空").append("<br>");
}else{
if(sfqy.equals("1")||sfqy.equals("0")){
}else{
errors.append("第"+(i+1)+"行的是否启用错误,1表示启用,0表示不启用").append("<br>");
}
}
omZy.setPcId(Long.valueOf(pcId).longValue());
omZy.setZydm(Long.valueOf(xydm).longValue());
omZy.setZymc(zymc);
omZy.setZyjc(zyjc);
omZy.setSfqy(sfqy);
omZy.setXydm(Long.valueOf(xydm));
omZy.setSfsc("0");
exlList.add(omZy);
}
}
}
if(errors!=null&&!"".equals(errors.toString())){
rDto.setErrMsg(errors.toString());
return rDto;
}
rDto.setResultBool(zyAppService.insertZyExcel(exlList));
} catch (Exception e) {
e.printStackTrace();
rDto.setErrMsg("模板错误,导入失败!");
rDto.setResultBool(false);
}
return rDto;
}
/**
* 判断表格中值的类型并且返回一个String类型的值
* @param cell
* @return
*/
private String getValue(Cell cell) {
if(cell!=null&&!"".equals(cell)){
cell.setCellType(Cell.CELL_TYPE_STRING);
}
if (cell == null)
return "";
if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue()).trim();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
double a = cell.getNumericCellValue();
return String.valueOf(a).trim();
} else {
return String.valueOf(cell.getStringCellValue()).trim();
}
}
注: Excel文件格式最好设置为文本类型,不然读取的时候会出问题