- 首先是上传文件,并读取文件(参考上一篇博客)。
- 首先获的需要读取的文件的路径和文件名。
// 创建输入流
//filePath 即为 要读取的文件 路径+文件名
InputStream stream = new FileInputStream(filePath);
// 获取Excel文件对象(使用输入流直接获取)
Workbook rwb = Workbook.getWorkbook(stream);
//读取第一个工作Sheet
Sheet rs = rwb.getSheet(0);
int clos = rs.getColumns();// 得到所有的列
int rows = rs.getRows();// 得到所有的行
//当在Excle文件表格中插入文本时,自定义一个格式。
WritableFont font1 = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.RED);
WritableWorkbook wbe = Workbook.createWorkbook(new File(filePath), rwb);
WritableSheet sheet = wbe.getSheet(0);
int falseNum = 0;
for (int i = 1; i < rows; i++) {
employeeName = rs.getCell(0, i).getContents();
email = rs.getCell(1, i).getContents();
workDate = rs.getCell(2, i).getContents();
score = rs.getCell(3, i).getContents();
if (employeeName != "" && email != "" && workDate != "" && score != "" && employeeName != null&& email != null && workDate != null && score != null) {
if (user != null) {
fileUserName = userService.selectUserByemail(email).getEmployeeName();
employeeId = userService.selectUserByemail(email).getEmployeeId();
if (!employeeName.equals(fileUserName)) {
WritableCellFormat format = new WritableCellFormat(font1);
Label label = new Label(4, i, "该员工姓名和邮箱不匹配!", format);
sheet.addCell(label);// 将改过的单元格保存到sheet
falseNum++;
continue;
} else {
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-mm-dd");
double s = Double.valueOf(score);
String exaTime = sdf2.format(sdf2.parse(workDate));
DayScore ds = dss.findScoreByUserIdDate(exaTime, employeeId);
if (ds == null) {
dss.addOssDayScore(employeeId, exaTime, proposer, s, "服务Excel导入");
} else {
dss.updateOssDayScore(employeeId, exaTime, s, proposer);
}
continue;
}
} else {
WritableCellFormat format = new WritableCellFormat(font1);
Label label = new Label(4, i, "邮箱错误,不能找到该邮箱!", format);
sheet.addCell(label);// 将改过的单元格保存到sheet
falseNum++;
}
} else {
WritableCellFormat format = new WritableCellFormat(font1);
Label label = new Label(4, i, "该员工信息不全!", format);
sheet.addCell(label);// 将改过的单元格保存到sheet
falseNum++;
}
}
if (falseNum == 0) {
message = "success";
WritableCellFormat format = new WritableCellFormat(font1);
Label label = new Label(1, rows, "倒入成功!", format);
sheet.addCell(label);// 将改过的单元格保存到sheet
} else {
message = "false";
WritableCellFormat format = new WritableCellFormat(font1);
Label label = new Label(1, rows, "导入失败!", format);
sheet.addCell(label);// 将改过的单元格保存到sheet
}
wbe.write();// 从内从中写入文件中
wbe.close();