From 6767bada39103d6ff65d76ba36a5b34e3b73d2b2 Mon Sep 17 00:00:00 2001 From: p9bwcp862 <2234458131@qq.com> Date: Thu, 10 Oct 2024 00:52:21 +0800 Subject: [PATCH] ADD file via upload --- data.js | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 data.js diff --git a/data.js b/data.js new file mode 100644 index 0000000..8a66131 --- /dev/null +++ b/data.js @@ -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}`); +}); \ No newline at end of file