|
|
@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
const express = require('express');
|
|
|
|
|
|
|
|
const app = express();
|
|
|
|
|
|
|
|
const mongoose = require('mongoose');
|
|
|
|
|
|
|
|
const xlsx = require('xlsx');
|
|
|
|
|
|
|
|
const fs = require('fs');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 连接MongoDB数据库
|
|
|
|
|
|
|
|
mongoose.connect('mongodb://localhost:27017/school', { useNewUrlParser: true, useUnifiedTopology: true });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const db = mongoose.connection;
|
|
|
|
|
|
|
|
db.on('error', console.error.bind(console, 'connection error:'));
|
|
|
|
|
|
|
|
db.once('open', function() {
|
|
|
|
|
|
|
|
console.log('Connected to the database');
|
|
|
|
|
|
|
|
// 读取并解析Excel文件
|
|
|
|
|
|
|
|
const workbook = xlsx.readFile('students.xlsx');
|
|
|
|
|
|
|
|
const sheetName = workbook.SheetNames[0]; // 假设只处理第一个工作表
|
|
|
|
|
|
|
|
const worksheet = workbook.Sheets[sheetName];
|
|
|
|
|
|
|
|
const studentsData = xlsx.utils.sheet_to_json(worksheet, { header: 1 }); // 将工作表转换为JSON数组,第一行是标题
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 创建一个临时数组来存储要保存的学生对象
|
|
|
|
|
|
|
|
const studentsToSave = [];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 遍历数据并创建学生对象
|
|
|
|
|
|
|
|
studentsData.forEach((student, index) => {
|
|
|
|
|
|
|
|
if (index === 0) return; // 跳过标题行
|
|
|
|
|
|
|
|
studentsToSave.push(new Student({
|
|
|
|
|
|
|
|
name: student.name,
|
|
|
|
|
|
|
|
id: student.id,
|
|
|
|
|
|
|
|
// points字段可以从Excel中读取,如果存在的话,否则使用默认值0
|
|
|
|
|
|
|
|
points: student.points ? Number(student.points) : 0
|
|
|
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 保存学生数据到数据库
|
|
|
|
|
|
|
|
Student.insertMany(studentsToSave, (err) => {
|
|
|
|
|
|
|
|
if (err) return console.error('Error saving students to the database:', err);
|
|
|
|
|
|
|
|
console.log('Students successfully saved to the database');
|
|
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 定义Student模型
|
|
|
|
|
|
|
|
const studentSchema = new mongoose.Schema({
|
|
|
|
|
|
|
|
name: String,
|
|
|
|
|
|
|
|
id: String,
|
|
|
|
|
|
|
|
points: { type: Number, default: 0 }
|
|
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const Student = mongoose.model('Student', studentSchema);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 创建API端点来提供学生数据
|
|
|
|
|
|
|
|
app.get('/api/students', async (req, res) => {
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
|
|
|
const students = await Student.find();
|
|
|
|
|
|
|
|
res.json(students);
|
|
|
|
|
|
|
|
} catch (err) {
|
|
|
|
|
|
|
|
res.status(500).json({ error: 'Failed to fetch students' });
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 启动服务器
|
|
|
|
|
|
|
|
const PORT = process.env.PORT || 3000;
|
|
|
|
|
|
|
|
app.listen(PORT, () => {
|
|
|
|
|
|
|
|
console.log(`Server is running on port ${PORT}`);
|
|
|
|
|
|
|
|
});
|