You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

121 lines
3.5 KiB

2 months ago
const express = require('express');
const multer = require('multer');
const XLSX = require('xlsx');
const cors = require('cors');
const app = express();
const port = 3000;
// 使用 CORS
app.use(cors());
// 设置 multer 存储配置
const storage = multer.memoryStorage();
const upload = multer({
storage: storage,
limits: { fileSize: 5 * 1024 * 1024 } // 5MB 限制
});
// 全局变量来存储学生数据
let dataArray = [];
let filePath = '';
// 处理文件上传的路由
app.post('/upload', upload.single('file'), (req, res) => {
try {
const file = req.file;
if (!file) {
return res.status(400).json({ message: 'No file uploaded.' });
}
// 使用 xlsx 库读取 Excel 文件
const workbook = XLSX.read(file.buffer, { type: 'buffer' });
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
// 初始化或更新全局的学生数据数组
dataArray = data.slice(1).map(row => ({
studentID: row[0], // 根据列的实际索引进行调整
name: row[1],
credit: row[2] || null
}));
// 处理数据(这里只是打印到控制台,你可以保存到数据库等)
console.log(data);
res.json({ message: 'File uploaded and processed successfully!' });
} catch (error) {
console.error('Error processing file:', error);
res.status(500).json({ message: 'Error processing file: ' + error.message });
}
});
// 新的API端点来返回随机学生数据
app.get('/api/get-random-student', (_, res) => {
if (dataArray.length === 0) {
return res.status(404).json({ error: 'No students found.' });
}
const randomIndex = Math.floor(Math.random() * dataArray.length);
const randomStudent = dataArray[randomIndex];
console.log('dataArray:', dataArray);
res.json(randomStudent);
});
// 新的API端点来增加学生的credit
app.post('/api/add-credit', express.json(), (req, res) => {
const { name, studentID } = req.body;
const student = dataArray.find(s => s.name === name && s.studentID === studentID);
if (!student) {
return res.status(404).json({ error: 'Student not found.' });
}
student.credit += 1;
console.log('Updated dataArray:', dataArray);
res.json({ message: 'Credit added successfully!' });
});
app.post('/api/credit', express.json(), (req, res) => {
const { name, studentID, creditToAdd } = req.body;
const student = dataArray.find(s => s.name === name && s.studentID === studentID);
if (!student) {
res.status(404).json({ message: 'Student not found!' });
return;
}
student.credit += parseInt(creditToAdd);
console.log('Updated dataArray:', dataArray);
res.json({ message: 'Credit added successfully!' });
// 创建一个新的工作簿
const workbook = XLSX.utils.book_new();
const worksheet = XLSX.utils.json_to_sheet(dataArray);
// 将工作表添加到工作簿
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
// 保存工作簿为 Excel 文件
const excelFilePath = 'C:/Users/Lenovo/Downloads/软工学生名单.xlsx';
XLSX.writeFile(workbook, excelFilePath);
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});