完成学生批量导入的接口

This commit is contained in:
zlm133588 2025-03-14 22:20:06 +08:00
parent 2f97a3466c
commit 8dc7233645
6 changed files with 626 additions and 1 deletions

View File

@ -47,4 +47,20 @@ export default {
findClassStudentsByIdPage: (data) => request.post('/classes/findClassStudentsByIdPage', data),
deleteClassStudentsById: (data) => request.post('/classes/deleteClassStudentsById', data),
getUserAdd: (data) => request.post('/user/getUserAdd', data),
importClassStudents: (config, data) =>
request({
url: '/importClassStudentsFile/importClassStudents',
method: 'post',
responseType: 'blob',
headers: { 'Content-Type': 'multipart/form-data' },
params: config,
data: data,
}),
download: (config) =>
request({
url: '/downloadFile/download',
method: 'get',
responseType: 'blob',
params: config,
}),
}

View File

@ -109,6 +109,77 @@
<artifactId>jedis</artifactId>
<version>3.8.0</version>
</dependency>
<!-- 文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- 获取上传视频时长依赖 -->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-all-deps</artifactId>
<version>3.3.1</version>
</dependency>
<!-- 导入外部的包-->
<dependency>
<groupId>org.apache.commons.collections</groupId>
<artifactId>commons-collections</artifactId>
<version>2.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/WEB-INF/lib/commons-collections-3.1.jar</systemPath>
</dependency>
<dependency>
<groupId>it.sauronsoftware.java</groupId>
<artifactId>sauronsoftware-java</artifactId>
<version>2.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/WEB-INF/lib/jave-1.0.2.jar</systemPath>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>apache-poi</artifactId>
<version>2.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/WEB-INF/lib/poi-3.6-20091214.jar</systemPath>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>com.csvreader</groupId>
<artifactId>csvreader</artifactId>
<version>2.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/WEB-INF/lib/javacsv.jar</systemPath>
</dependency>
<dependency>
<groupId>jakarta.mail</groupId>
<artifactId>jakarta.mail-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.5.29</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
@ -119,6 +190,23 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.opensymphony</groupId>
<artifactId>xwork</artifactId>
<version>2.3.20</version> <!-- 请根据需要选择合适的版本 -->
</dependency>
<!-- 中文拼音 -->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>javax.xml.ws</groupId>
<artifactId>jaxws-api</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
</dependencyManagement>

View File

@ -0,0 +1,142 @@
package com.example.aes.user.controller;
import cn.hutool.core.io.FileUtil;
import com.example.aes.global.model.RespBean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@RestController
@RequestMapping("/downloadFile")
public class DownLoadFileController {
private final ResourceLoader resourceLoader;
public DownLoadFileController(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@GetMapping("/download")
public RespBean download(String fileName, HttpServletResponse response) throws IOException {
ServletOutputStream outputStream = null;
try {
response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
outputStream = response.getOutputStream();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
// File file = new File(root + File.separator + fileName);
// System.out.println(root + File.separator + fileName);
//加载资源文件
Resource resource = resourceLoader.getResource("classpath:file" + File.separator + fileName);
InputStream inputStream = resource.getInputStream();
// 创建临时文件
File file = File.createTempFile(FileUtil.mainName(fileName), "."+FileUtil.extName(fileName));
// 将资源文件内容复制到临时文件中
try (FileOutputStream fileoutputStream = new FileOutputStream(file)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileoutputStream.write(buffer, 0, bytesRead);
}
}
// 下载
if(file.exists()){
//从文件中读到的内容
InputStream fis = new FileInputStream(file);
// System.out.println("File存在");
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buff = new byte[1024];
int size;
while((size = bis.read(buff))!=-1){
outputStream.write(buff,0,size);
}
bis.close();
fis.close();
}else{
outputStream.write(new String("No Such File!").getBytes());
}
outputStream.flush();
outputStream.close();
return RespBean.ok("importClassStudentModel");
}
@GetMapping("/downloadTestOut")
public RespBean downloadTestOut(String fileNameOut, String fileNameIn, HttpServletResponse response) throws IOException{
String prefix = "dhuoj://";
String baseDirOut = "C:" + File.separator + "OJtemp" + File.separator + "testcaseOut" + File.separator;
String baseDirIn = "C:" + File.separator + "OJtemp" + File.separator + "testcaseIn" + File.separator;
File tempZipFile = File.createTempFile("download", ".zip");
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempZipFile))) {
// Add fileNameOut to ZIP
if (fileNameOut.startsWith(prefix)) {
String outputPath = baseDirOut + fileNameOut.substring(prefix.length());
addFileToZip(outputPath, "TestOut.txt", zos);
}
// Add fileNameIn to ZIP (assuming it also follows the same prefix and directory structure)
if (fileNameIn.startsWith(prefix)) {
String inputPath = baseDirIn + fileNameIn.substring(prefix.length());
addFileToZip(inputPath, "TestIn.txt", zos);
}
}
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("files.zip", "UTF-8"));
try (ServletOutputStream outputStream = response.getOutputStream();
FileInputStream fis = new FileInputStream(tempZipFile)) {
byte[] buffer = new byte[1024];
int size;
while ((size = fis.read(buffer)) != -1) {
outputStream.write(buffer, 0, size);
}
outputStream.flush();
} finally {
// Clean up temporary file
tempZipFile.delete();
}
return RespBean.ok("AnswerTestOut");
}
private void addFileToZip(String filePath, String entryName, ZipOutputStream zos) throws IOException{
File file = new File(filePath);
if (file.exists()) {
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis)) {
zos.putNextEntry(new ZipEntry(entryName));
byte[] buffer = new byte[1024];
int size;
while ((size = bis.read(buffer)) != -1) {
zos.write(buffer, 0, size);
}
zos.closeEntry();
}
} else {
zos.putNextEntry(new ZipEntry(entryName));
zos.write("No Such File!".getBytes());
zos.closeEntry();
}
}
}

View File

@ -0,0 +1,378 @@
package com.example.aes.user.controller;
import cn.hutool.core.io.FileUtil;
import com.example.aes.global.model.RespBean;
import com.example.aes.user.dao.AdminusersDaoI;
import com.example.aes.user.dao.ClassesDaoI;
import com.example.aes.user.dao.ClassstudentsDaoI;
import com.example.aes.user.model.Adminusers;
import com.example.aes.user.model.Classes;
import com.example.aes.user.model.PMUser;
import com.example.aes.user.model.Users;
import com.example.aes.user.service.UserServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/importClassStudentsFile")
@Transactional
public class importClassStudentsFileController{
// private File upload;
// private String uploadContentType;
// private String uploadFileName;
// private String savePath;
// int classId;
@Autowired
private UserServiceI userService;
@Autowired
private ClassstudentsDaoI classstudentsDao;
@Resource
private ClassesDaoI classesDao;
@Autowired
private AdminusersDaoI adminusersDao;
// ApplicationHome home = new ApplicationHome(importClassStudentsFileController.class);
// String jarPath = home.getSource().getParentFile().toString();
// public void setSavePath(String value) {
// this.savePath = value;
// }
//
// private String getSavePath() throws Exception {
// return ServletActionContext.getServletContext().getRealPath("/file/");
// }
// public void setUpload(File upload) {
// this.upload = upload;
// }
//
// public File getUpload() {
// return this.upload;
// }
// public void setUploadContentType(String uploadContentType) {
// this.uploadContentType = uploadContentType;
// }
//
// public String getUploadContentType() {
// return this.uploadContentType;
// }
// public void setUploadFileName(String uploadFileName) {
// this.uploadFileName = uploadFileName;
// }
//
// public String getUploadFileName() {
// return this.uploadFileName;
// }
// @PostMapping("/upload")
// @ResponseBody
// public RespBean upload(MultipartFile file) throws IOException {
// Calendar c = Calendar.getInstance();// 可以对每个时间域单独修改
// String year = String.valueOf(c.get(Calendar.YEAR));
// String month = String.valueOf(c.get(Calendar.MONTH));
// if (month.length() == 1)
// month = "0" + month;
// String date = String.valueOf(c.get(Calendar.DATE));
// if (date.length() == 1)
// date = "0" + date;
// String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
// if (hour.length() == 1)
// hour = "0" + hour;
// String minute = String.valueOf(c.get(Calendar.MINUTE));
// if (minute.length() == 1)
// minute = "0" + minute;
// String second = String.valueOf(c.get(Calendar.SECOND));
// if (second.length() == 1)
// second = "0" + second;
// String[] temp = uploadFileName.split("\\.");
// String ext = "." + temp[1]; // 得到文件后缀
// if (ext.equals(".csv") == false)
// return "FAIL";
// uploadFileName = year + "" + month + "" + date + "" + hour + ""
// + minute + "" + second + ext; // 以时间作为文件名
// FileOutputStream fos;
// try {
// fos = new FileOutputStream(getSavePath() + "\\"
// + getUploadFileName());
// FileInputStream fis = new FileInputStream(getUpload());
// byte[] buffer = new byte[1024];
// int len = 0;
// while ((len = fis.read(buffer)) > 0) {
// fos.write(buffer, 0, len);
// }
// fos.close();
// fis.close();
// boolean result = decodeFile(getSavePath() + "\\"
// + getUploadFileName()); // 解析文件
// if (result == false) {
// // System.out.println(getSavePath()+"\\"+getUploadFileName()+"文件格式不正确!");
// File file = new File(getSavePath() + "\\" + getUploadFileName());
// file.delete();
// return "FAIL";
// }
// // System.out.println(getSavePath()+"\\"+getUploadFileName()+"文件解析成功!");
// File file = new File(getSavePath() + "\\" + getUploadFileName()); // 删除文件
// file.delete();
// return "SUCCESS";
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// // System.out.println(getUploadFileName()+"上传失败!");
// return "FAIL";
// }
//
// }
// @Override
// public String execute() {
// Calendar c = Calendar.getInstance();// 可以对每个时间域单独修改
// String year = String.valueOf(c.get(Calendar.YEAR));
// String month = String.valueOf(c.get(Calendar.MONTH));
// if (month.length() == 1)
// month = "0" + month;
// String date = String.valueOf(c.get(Calendar.DATE));
// if (date.length() == 1)
// date = "0" + date;
// String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
// if (hour.length() == 1)
// hour = "0" + hour;
// String minute = String.valueOf(c.get(Calendar.MINUTE));
// if (minute.length() == 1)
// minute = "0" + minute;
// String second = String.valueOf(c.get(Calendar.SECOND));
// if (second.length() == 1)
// second = "0" + second;
// String[] temp = uploadFileName.split("\\.");
// String ext = "." + temp[1]; // 得到文件后缀
// if (ext.equals(".csv") == false)
// return "FAIL";
// uploadFileName = year + "" + month + "" + date + "" + hour + ""
// + minute + "" + second + ext; // 以时间作为文件名
// FileOutputStream fos;
// try {
// fos = new FileOutputStream(getSavePath() + "\\"
// + getUploadFileName());
// FileInputStream fis = new FileInputStream(getUpload());
// byte[] buffer = new byte[1024];
// int len = 0;
// while ((len = fis.read(buffer)) > 0) {
// fos.write(buffer, 0, len);
// }
// fos.close();
// fis.close();
// boolean result = decodeFile(getSavePath() + "\\"
// + getUploadFileName()); // 解析文件
// if (result == false) {
// // System.out.println(getSavePath()+"\\"+getUploadFileName()+"文件格式不正确!");
// File file = new File(getSavePath() + "\\" + getUploadFileName());
// file.delete();
// return "FAIL";
// }
// // System.out.println(getSavePath()+"\\"+getUploadFileName()+"文件解析成功!");
// File file = new File(getSavePath() + "\\" + getUploadFileName()); // 删除文件
// file.delete();
// return "SUCCESS";
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// // System.out.println(getUploadFileName()+"上传失败!");
// return "FAIL";
// }
//
// }
@PostMapping("/importClassStudents")
public RespBean importClassStudents(MultipartFile file, int classId) throws IOException{
// 获取文件原始名
String uploadFileName = file.getOriginalFilename();
// 获取主要名称
String mainName = FileUtil.mainName(uploadFileName);
// 获取文件后缀名
String extName = FileUtil.extName(uploadFileName);
// 用当前时间避免重复
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
Date date1 = new Date();
String timeStamp = formatter.format(date1);
// 获取时间戳
long timestamp = System.currentTimeMillis(); // 获取当前时间戳(单位:毫秒)
String timeStampStr = Long.toString(timestamp); // 将时间戳转换为字符串类型
Calendar c = Calendar.getInstance();// 可以对每个时间域单独修改
String year = String.valueOf(c.get(Calendar.YEAR));
String month = String.valueOf(c.get(Calendar.MONTH));
if (month.length() == 1)
month = "0" + month;
String date = String.valueOf(c.get(Calendar.DATE));
if (date.length() == 1)
date = "0" + date;
String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
if (hour.length() == 1)
hour = "0" + hour;
String minute = String.valueOf(c.get(Calendar.MINUTE));
if (minute.length() == 1)
minute = "0" + minute;
String second = String.valueOf(c.get(Calendar.SECOND));
if (second.length() == 1)
second = "0" + second;
String[] temp = uploadFileName.split("\\.");
String ext = "." + temp[1]; // 得到文件后缀
// 如果文件不是以csv结尾的
if (ext.equals(".csv") == false)
return RespBean.error("FAIL");
// 用来保存的文件名
uploadFileName = year + "" + month + "" + date + "" + hour + ""
+ minute + "" + second + ext; // 以时间作为文件名
try {
String root = System.getProperty("user.dir")+ File.separator + "upload";
String left = "classStudentFile" + File.separator + timeStamp + File.separator;
// 文件存储
String resultPath = root + File.separator + left;
if(!FileUtil.exist(resultPath))
FileUtil.mkdir(resultPath);
String decodeFileName = resultPath + mainName + timeStampStr + "." + extName;
// 存储文件到服务器
file.transferTo(new File(decodeFileName));
// 解析文件
boolean result = decodeFile(decodeFileName, classId);
if (result == false) {
File file1 = new File(decodeFileName);
file1.delete();
return RespBean.error("FAIL");
}
File file1 = new File(decodeFileName); // 删除文件
file1.delete();
return RespBean.ok("SUCCESS");
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// System.out.println(getUploadFileName()+"上传失败!");
return RespBean.error("FAIL");
}
}
@Transactional
public boolean decodeFile(String fileName, int classId) // 解析csv文件
{
// String filePath = System.getProperty("user.dir")+"\\upload\\classStudentFile\\" + fileName;
File file = new File(fileName);
// File file = new File(fileName);
List<PMUser> userList = new ArrayList<PMUser>();
try {
// InputStream fis = new FileInputStream(file);
// FileReader in1 = new FileReader(file);
// BufferedReader in2 = new BufferedReader(in1);
FileInputStream fis = new FileInputStream(file);
InputStreamReader in1 = new InputStreamReader(fis, "GBK");
BufferedReader in2 = new BufferedReader(in1);
String s = "";
String row[];
s = in2.readLine();
row = s.split(",");
if (row[0].equals("学号") && row[1].equals("姓名")
&& row[2].equals("自然班级")) {
while ((s = in2.readLine()) != null) {
row = s.split(",");
if (row.length < 2)
return false;
String studentNo = row[0];
String chineseName = row[1];
String banji = row[2];
PMUser user = new PMUser(); // 将信息存储
user.setStudentNo(studentNo);
user.setChineseName(chineseName);
user.setBanji(banji);
userList.add(user);
}
Classes onclass = classesDao.get(Classes.class, classId);
if (onclass != null) {
int teacherId = onclass.getTeacherId();
Adminusers adminuser = adminusersDao.get(Adminusers.class,
teacherId);
if (adminuser != null) {
// int schoolId = adminuser.getSchoolId();
// 开始导入信息
for (int i = 0; i < userList.size(); i++) {
PMUser p = userList.get(i);
// p.setSchoolId(schoolId);
String studentNo = p.getStudentNo();
Users user = userService
.findUserByStudentNo(studentNo); // 用户信息
if (user != null) // users表中存在用户则只在classStudents表中插入数据并且更新学生班级
{
user.setBanji(p.getBanji());
boolean updateresult = userService.updateStudentBanji(user);
if(updateresult){
int id = user.getId();
boolean result = classstudentsDao
.findClassStudentByUserId(id, classId); // 如果为true则表明该学生已在表中
if (result == false){
result = classstudentsDao
.insertClassStudent(id, classId); // 将用户插入classstudents表
}
}
} else {
p = userList.get(i);
boolean result = userService.insertUser(p);
if (result == true) {
studentNo = p.getStudentNo();
user = userService
.findUserByStudentNo(
studentNo);
int id = user.getId();
result = classstudentsDao
.insertClassStudent(id, classId); // 将用户插入classstudents表
}
}
}
// 更新学生人数
int studentsNum = classstudentsDao
.getClassStudentsNum(classId);
boolean result = classesDao.updateClassStudentsNum(
classId, studentsNum);
}
else {
return false;
}
}
else {
return false;
}
} else {
return false;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}

View File

@ -414,7 +414,7 @@ public class UserServiceImpl implements UserServiceI {
String time = dateFormat.format(createDate);
// TODO Auto-generated method stub
String hql = "update Users set banji='" + user.getBanji()
+ "'where studentNo='" + user.getStudentNo();
+ "'where studentNo='" + user.getStudentNo()+"'";
int result = userDao.executeHql(hql);
if (result == 1)
return true;

View File

@ -0,0 +1 @@
学号,姓名,自然班级
1 学号 姓名 自然班级