前言:公司有项目需要用到导入excel数据进行数据统计分析,进行对比后,发现jxls比poi少写不少代码,api调用也相当方便。从而在项目中采用此技术,特辑之。(阐述方式从底层到视图层)
1、确定excel文档中个字段的含义和文档格式。
2、对应编写excel相近的xml模板文件:
//sheet名字
attendanceData.number
attendanceData.attendNum
attendanceData.selfDefineNum
attendanceData.name
attendanceData.isCapacityArrange
attendanceData.attendDate
attendanceData.correspondingStep
attendanceData.openTime
attendanceData.closingTime
attendanceData.signInTime
attendanceData.signOutTime
attendanceData.dueNum
attendanceData.trueNum
attendanceData.lateTime
attendanceData.earlyTime
attendanceData.isAbsent
attendanceData.overtimeTime
attendanceData.workTime
attendanceData.exceptionalCase
attendanceData.isAttend
attendanceData.isSignOut
attendanceData.dept
attendanceData.usual
attendanceData.weekend
attendanceData.holiday
attendanceData.attendTime
attendanceData.usualOvertime
attendanceData.weekendOvertime
attendanceData.holidayOvertime
3、编写对应的vo类:
public class AttendanceData {
private String number;//序号
private String attendNum;//考勤号码
private String selfDefineNum;//自定义编号
private String name;//姓名
private String isCapacityArrange;//是否智能排班(true?false字段)
private String attendDate;
private String correspondingStep;//对应时段
private String openTime;//上班时间
private String closingTime;//下班时间
private String signInTime;//签到时间
private String signOutTime;//签退时间
private String dueNum;//应到
private String trueNum;//实到
private String lateTime;//迟到时间
private String earlyTime;//早退时间
private String isAbsent;//是否旷工
private String overtimeTime;//加班时间
private String workTime;//工作时间
private String exceptionalCase;//例外情况
private String isAttend;//应签到
private String isSignOut;//应签退
private String dept;//部门
private String usual;//平日
private String weekend;//周末
private String holiday;//节假日
private String attendTime;//出勤时间/工作时间
private String usualOvertime;//平日加班
private String weekendOvertime;//周末加班
private String holidayOvertime;//节假日加班
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getAttendNum() {
return attendNum;
}
public void setAttendNum(String attendNum) {
this.attendNum = attendNum;
}
public String getSelfDefineNum() {
return selfDefineNum;
}
public void setSelfDefineNum(String selfDefineNum) {
this.selfDefineNum = selfDefineNum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsCapacityArrange() {
return isCapacityArrange;
}
public void setIsCapacityArrange(String isCapacityArrange) {
this.isCapacityArrange = isCapacityArrange;
}
public String getAttendDate() {
return attendDate;
}
public void setAttendDate(String attendDate) {
this.attendDate = attendDate;
}
public String getCorrespondingStep() {
return correspondingStep;
}
public void setCorrespondingStep(String correspondingStep) {
this.correspondingStep = correspondingStep;
}
public String getOpenTime() {
return openTime;
}
public void setOpenTime(String openTime) {
this.openTime = openTime;
}
public String getClosingTime() {
return closingTime;
}
public void setClosingTime(String closingTime) {
this.closingTime = closingTime;
}
public String getSignInTime() {
return signInTime;
}
public void setSignInTime(String signInTime) {
this.signInTime = signInTime;
}
public String getSignOutTime() {
return signOutTime;
}
public void setSignOutTime(String signOutTime) {
this.signOutTime = signOutTime;
}
public String getDueNum() {
return dueNum;
}
public void setDueNum(String dueNum) {
this.dueNum = dueNum;
}
public String getTrueNum() {
return trueNum;
}
public void setTrueNum(String trueNum) {
this.trueNum = trueNum;
}
public String getLateTime() {
return lateTime;
}
public void setLateTime(String lateTime) {
this.lateTime = lateTime;
}
public String getEarlyTime() {
return earlyTime;
}
public void setEarlyTime(String earlyTime) {
this.earlyTime = earlyTime;
}
public String getIsAbsent() {
return isAbsent;
}
public void setIsAbsent(String isAbsent) {
this.isAbsent = isAbsent;
}
public String getOvertimeTime() {
return overtimeTime;
}
public void setOvertimeTime(String overtimeTime) {
this.overtimeTime = overtimeTime;
}
public String getWorkTime() {
return workTime;
}
public void setWorkTime(String workTime) {
this.workTime = workTime;
}
public String getExceptionalCase() {
return exceptionalCase;
}
public void setExceptionalCase(String exceptionalCase) {
this.exceptionalCase = exceptionalCase;
}
public String getIsAttend() {
return isAttend;
}
public void setIsAttend(String isAttend) {
this.isAttend = isAttend;
}
public String getIsSignOut() {
return isSignOut;
}
public void setIsSignOut(String isSignOut) {
this.isSignOut = isSignOut;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getUsual() {
return usual;
}
public void setUsual(String usual) {
this.usual = usual;
}
public String getWeekend() {
return weekend;
}
public void setWeekend(String weekend) {
this.weekend = weekend;
}
public String getHoliday() {
return holiday;
}
public void setHoliday(String holiday) {
this.holiday = holiday;
}
public String getAttendTime() {
return attendTime;
}
public void setAttendTime(String attendTime) {
this.attendTime = attendTime;
}
public String getUsualOvertime() {
return usualOvertime;
}
public void setUsualOvertime(String usualOvertime) {
this.usualOvertime = usualOvertime;
}
public String getWeekendOvertime() {
return weekendOvertime;
}
public void setWeekendOvertime(String weekendOvertime) {
this.weekendOvertime = weekendOvertime;
}
public String getHolidayOvertime() {
return holidayOvertime;
}
public void setHolidayOvertime(String holidayOvertime) {
this.holidayOvertime = holidayOvertime;
}
}
4、service类中进行数据处理(读excel内容),其中xml模板文件写配置:
private final static String xmlConfig = "attendanceData.xml";
@Override
public List importAttendData(String filePath) {
XLSReader mainReader;
try {
InputStream inputXML = new BufferedInputStream(getClass().getClassLoader().getResourceAsStream(xmlConfig));
mainReader = ReaderBuilder.buildFromXML(inputXML);
InputStream inputXLS = new BufferedInputStream(new FileInputStream(filePath));
List attendanceDatas = new ArrayList<>();
Map beans = new HashMap();
beans.put("attendanceDatas", attendanceDatas);
XLSReadStatus readStatus = mainReader.read(inputXLS, beans);
return attendanceDatas;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
}
return null;
}
5、controller类进行接口调用:
@RequestMapping(value = "importAttendData", method = RequestMethod.POST)
@ResponseBody
public ResponseResult importTestResult(MultipartFile myfile, HttpServletRequest req) throws Exception {
ResponseResult responseResult = new ResponseResult();
String templateFile = req.getSession().getServletContext().getRealPath("/import");
try {
if (myfile.isEmpty()) {
responseResult.setResult(Result.WARNING);
responseResult.setMessage("导入文件为空!!");
return responseResult;//URLEncoder.encode("[<导入文件为空!!>]", "UTF-8");
} else {
String fileName = myfile.getOriginalFilename();
if (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx") && !fileName.endsWith(".xlsm")) {
responseResult.setResult(Result.WARNING);
responseResult.setMessage("文件类型错误,导入文件仅允许excel文件类型!!");
return responseResult;
}
File file = new File(templateFile);
if (!file.exists()) {
file.mkdirs();
}
FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(templateFile, myfile.getOriginalFilename()));
String resultFilePath = templateFile + File.separator + fileName;
List testReportResults = attendanceService.importAttendData(resultFilePath);
String errorInfo = "";
if (testReportResults != null) {
//i从1开始,忽略模板中的标题栏
StringBuilder stringBuilder = attendanceService.updateAttendDataByCode(testReportResults);
if (stringBuilder.length() > 0) {
String inf = stringBuilder.toString();
responseResult.setResult(Result.WARNING);
responseResult.setMessage(inf);
return responseResult;
// return java.net.URLEncoder.encode("[<" + inf + ">]", "UTF-8");
} else {
responseResult.setResult(Result.SUCCESS);
responseResult.setMessage("导入成功!!");
return responseResult;
// return "SUCCESS";//URLEncoder.encode("[<导入成功!!>]", "UTF-8");
}
} else {
responseResult.setResult(Result.FAILURE);
responseResult.setMessage("导入文件内容格式错误!!");
return responseResult;
// return java.net.URLEncoder.encode("[<导入文件内容格式错误!!>]", "UTF-8"); //URLEncoder.encode("[<导入文件内容格式错误!!>]", "UTF-8");
}
}
} catch (Exception e) {
e.printStackTrace();
responseResult.setResult(Result.FAILURE);
responseResult.setMessage("系统正忙,请稍后再试!!");
return responseResult;
// return java.net.URLEncoder.encode("[<系统正忙,请稍后再试!!>]", "UTF-8");
}
}
6、视图层jsp通过ajax进行数据导入:
6.1、弹出模态框进行数据导入
6.2 excel文档导入提交
function importReportResult() {
var reportId = $("#reportId").val();
if (confirm("确定导入考勤数据?")) {
$("#log").val("正在导入中...");
$("#submitReportResult").ajaxSubmit({
type: 'post',
url: "../assets/importAttendData.do",
success: function (data) {
var dataContent = JSON.stringify(decodeURI(data));
dataContent = dataContent.substring(dataContent.lastIndexOf("[<") + 2, dataContent.lastIndexOf(">]"));
var content1 = dataContent.substring(0, dataContent.lastIndexOf("!!") + 2);
var content2 = dataContent.substring(dataContent.lastIndexOf("!!") + 2, dataContent.length - 2);
if (content1 == "导入成功!!") {
$("#log").val(content1 + "\n" + content2);
$("#grid").data("kendoGrid").dataSource.read();
// $('#submit').disabled=false;
} else {
$("#log").val(dataContent);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
$("#log").val("导入异常!");
}
});
}
}
或者
function importReportResult() {
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
/* if (userAgent.indexOf("Opera") > -1) {
return "Opera"
}; //判断是否Opera浏览器
if (userAgent.indexOf("Firefox") > -1) {
return "FF";
} //判断是否Firefox浏览器*/
var reportId = $("#reportId").val();
if (confirm("确定导入考勤数据?")) {
$("#log").val("正在导入中...");
$("#submitReportResult").ajaxSubmit({
type: 'post',
url: "../assets/importAttendData.do",
data:$(this).serialize(),
dataType:"text",
success: function (data) {
if (userAgent.indexOf("Chrome") > -1){
var reg = /(.+)<\/pre>/g;
var result = data.match(reg);
data = RegExp.$1;
data = JSON.parse(data);
console.info(data.result);
}
if (data.result == "SUCCESS") {
$("#log").val("导入成功");
$("#grid").data("kendoGrid").dataSource.read();
} else {
$("#log").val(data.message);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
$("#log").val("导入异常!");
}
});
}
}
7、后记,其实jxsl技术还可以进行很好的excel模板导出操作,后续在进行阐述。
参考文档:
https://www.cnblogs.com/lilongsheng1125/p/4978522.html
http://blog.csdn.net/u010402228/article/details/50155771
https://www.cnblogs.com/foxlee1024/p/7616987.html