导入依赖
<!--SpringBoot整合jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--报表导入导出-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
前端HTML5代码:
<form th:action="@{/admin/upload}" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Excel文件</label>
<input type="file" name="file" id="file" class="form-control">
</div>
<input type="button" onclick="sendFile()" value="上传" class="btn btn-primary"/>
</form>
JavaScript 代码:
<script type="text/javascript">
function sendFile() {
var file = $("input[name='file']").val();
if (file == "") {
alert("请选择上传的目标文件! ")
return false;
}
var file1 = file.substring(file.lastIndexOf(".") + 1).toLowerCase();
if(file1 != "xls" && file1 !="xlsx"){
alert("请选择Execl文件!");
$("input[name='file']").val("");
return false;
}
var size1 = $("input[name='file']")[0].files[0].size;
if (size1>104857600) {
alert("上传文件不能大于100M!");
return false;
}
var formData = new FormData();
formData.append("file",$("#file")[0].files[0]);
$.ajax({
type : "post",
url : "http://localhost:8080/admin/upload",
data : formData,
processData : false,
contentType : false,
success : function(data){
if (data.code == "0" && data.code == "5") {
alert("文件上传成功!");
window.location.href = "http://localhost:8080/admin/listStudent";
}else if (data.code == "1") {
alert("导入的Excel表中学生年龄数据格式不正确!");
}else if (data.code == "2") {
alert("导入的Excel表中学生数据存在空值!");
$("input[name='file']").val("");
}else{
alert("导入的Excel表中数据有误,请检查上传的Excel文档(没用数据或字段格式有误或字段存在空值!");
$("input[name='file']").val("");
}
}
});
}
dao层代码:
public interface StudentDao extends JpaRepository<Student,Integer>, JpaSpecificationExecutor<Student> {
@Query(value = "select * from Student where id = ?1",nativeQuery = true)
Student findBystuId(Integer id);
@Query(value = "select * from Student where id_card = ?1",nativeQuery = true)
Student findByIdCard(String idCard);
}
后端Service实现类代码:
@Override
public Map<String,String> addStudent(MultipartFile file, HttpSession session) throws IOException, AgeFormatException, DataNullPointerException {
Map<String,String> map = new HashMap();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
List<String[]> list = POIUtil.readExcel(file);
if (CollectionUtils.isEmpty(list)) {
map.put("code", MessageConstantUtil.EXCEL_NULL);
throw new NullPointerException("数据为空");
}else {
List<Student> data = new ArrayList<>();
for (String[] strings : list) {
String name = strings[0];
String idCard = strings[1];
String ageStr = strings[2];
String address = strings[3];
map = operateCommon.addStudentCommons(name, idCard, ageStr, address, timestamp, session);
}
}
return map;
}
提取的公共部分代码:
@Component
public class OperateCommon {
@Autowired
private StudentDao studentDao;
@Autowired
private RedisTemplate<String,String> redisTemplate;
public Map<String,String> addStudentCommons(String name, String idCard, String ageStr, String address, Timestamp timestamp, HttpSession session) throws AgeFormatException, DataNullPointerException {
Map<String,String> map = new HashMap();
int adminId = (int) session.getAttribute("adminId");
boolean compareAll = compareAll(name, idCard, ageStr, address);
if (compareAll) {
if (ageStr.matches(ConstantUtil.AGEREG) && idCard.matches(ConstantUtil.IDCARDREG)) {
Student stuIdCard = studentDao.findByIdCard(idCard);
int age = Integer.parseInt(ageStr);
if (stuIdCard == null) {
Student student = new Student(name, idCard, age, address, ConstantUtil.UNSTUDENTSTATUS);
student.setCreateId(adminId);
student.setCreateTime(timestamp);
studentDao.save(student);
Student byIdCard = studentDao.findByIdCard(idCard);
String s = JSON.toJSONString(byIdCard);
redisTemplate.boundSetOps("studentInfo").add(s);
map.put("code", MessageConstantUtil.ADD_STUDENT_SUCCESS);
} else {
stuIdCard.setName(name);
stuIdCard.setIdCard(idCard);
stuIdCard.setAge(age);
stuIdCard.setAddress(address);
stuIdCard.setUpdateId(adminId);
stuIdCard.setUpdateTime(timestamp);
stuIdCard.setStudentStatus(ConstantUtil.UNSTUDENTSTATUS);
Set<String> studentInfo = redisTemplate.boundSetOps("studentInfo").members();
for (String stu : studentInfo) {
Student student = JSON.parseObject(stu, Student.class);
boolean compareStudents = compareStudents(stuIdCard, student);
if (compareStudents){
String stu1 = JSON.toJSONString(student);
redisTemplate.boundSetOps("studentInfo").remove(stu1);
student.setName(name);
student.setIdCard(idCard);
student.setAge(age);
student.setAddress(address);
student.setUpdateId(adminId);
student.setUpdateTime(timestamp);
student.setStudentStatus(ConstantUtil.UNSTUDENTSTATUS);
String newStu = JSON.toJSONString(student);
redisTemplate.boundSetOps("studentInfo").add(newStu);
}
}
studentDao.save(stuIdCard);
map.put("code", MessageConstantUtil.UPDATE_STUDENT_SUCCESS);
}
}else {
map.put("code",MessageConstantUtil.NUM_FORMAT_FAIT);
throw new AgeFormatException("表中学生年龄或身份证数据格式不正确!");
}
}else {
map.put("code",MessageConstantUtil.DATA_NULL_POINT);
throw new DataNullPointerException("表中学生数据存在空值!");
}
return map;
}
public boolean compareAll(String name, String idCard, String ageStr, String address){
boolean nameFlag = true;
boolean idCardFlag = true;
boolean ageFlag = true;
boolean addressFlag = true;
if (name == "" || name == null){
nameFlag = false;
}
if (idCard == "" || idCard == null){
idCardFlag = false;
}
if (ageStr == "" || ageStr == null){
ageFlag = false;
}
if (address == "" || address == null){
addressFlag = false;
}
if (nameFlag && idCardFlag && ageFlag && addressFlag) {
return true;
}else {
return false;
}
}
public boolean compareStudents(Student student1, Student student2){
boolean nameFlag = true;
boolean idCardFlag = true;
boolean ageFlag = true;
boolean addressFlag = true;
boolean statusFlag = true;
if (student1.getName().equals(student2.getName())){
nameFlag = false;
}
if (student1.getIdCard().equals(student2.getIdCard())){
idCardFlag = false;
}
if (student1.getAge().equals(student2.getAge())){
ageFlag = false;
}
if (student1.getAddress().equals(student2.getAddress())){
addressFlag = false;
}
if (student1.getId().equals(student2.getId()) &&(nameFlag||idCardFlag||ageFlag||addressFlag)){
return true;
}else {
return false;
}
}
}
controller 代码:
@Transactional(rollbackFor = Exception.class)
@PostMapping("/upload")
@ResponseBody
public Map<String,String> upload(@RequestParam("file") MultipartFile file, HttpSession session){
try {
return studentService.addStudent(file, session);
} catch (AgeFormatException e) {
e.printStackTrace();
} catch (DataNullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
POIUtil工具包:
public class POIUtil {
private final static String xls = "xls";
private final static String xlsx = "xlsx";
private final static String DATE_FORMAT = "yyyy/MM/dd";
public static List<String[]> readExcel(MultipartFile file) throws IOException {
checkFile(file);
Workbook workbook = getWorkBook(file);
List<String[]> list = new ArrayList<String[]>();
if(workbook != null){
for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
Sheet sheet = workbook.getSheetAt(sheetNum);
if(sheet == null){
continue;
}
int firstRowNum = sheet.getFirstRowNum();
int lastRowNum = sheet.getLastRowNum();
for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){
Row row = sheet.getRow(rowNum);
if(row == null){
continue;
}
int firstCellNum = row.getFirstCellNum();
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
}
workbook.close();
}
return list;
}
public static void checkFile(MultipartFile file) throws IOException{
if(null == file){
throw new FileNotFoundException("文件不存在!");
}
String fileName = file.getOriginalFilename();
if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){
throw new IOException(fileName + "不是excel文件");
}
}
public static Workbook getWorkBook(MultipartFile file) {
String fileName = file.getOriginalFilename();
Workbook workbook = null;
try {
InputStream is = file.getInputStream();
if(fileName.endsWith(xls)){
workbook = new HSSFWorkbook(is);
}else if(fileName.endsWith(xlsx)){
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}
public static String getCellValue(Cell cell){
String cellValue = "";
if(cell == null){
return cellValue;
}
String dataFormatString = cell.getCellStyle().getDataFormatString();
if(dataFormatString.equals("m/d/yy")){
cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue());
return cellValue;
}
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
cell.setCellType(Cell.CELL_TYPE_STRING);
}
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC:
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK:
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR:
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
}
excel模板样式