From 00f8284aa94ad9d2a5e933992a876604a0189898 Mon Sep 17 00:00:00 2001 From: p34h2feab <2067143228@qq.com> Date: Sun, 13 Oct 2024 00:26:20 +0800 Subject: [PATCH] ADD file via upload --- cloud index.js | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 cloud index.js diff --git a/cloud index.js b/cloud index.js new file mode 100644 index 0000000..dbde63d --- /dev/null +++ b/cloud index.js @@ -0,0 +1,52 @@ +const cloud = require('wx-server-sdk'); +cloud.init(); + +// 引入 xlsx 库用于解析 Excel 文件 +const XLSX = require('xlsx'); + +exports.main = async (event, context) => { + const { fileID } = event; + const db = cloud.database(); + const _ = db.command; + + try { + console.log('Starting to import students...'); + + // 下载文件 + const downloadResult = await cloud.downloadFile({ fileID }); + const fileBuffer = downloadResult.fileContent; + console.log('File content:', fileBuffer.toString()); + + // 使用 xlsx 库解析 Excel 文件 + const workbook = XLSX.read(fileBuffer, { type: 'buffer' }); + const sheetName = workbook.SheetNames[0]; + const worksheet = workbook.Sheets[sheetName]; + + // 手动跳过第一行(标题行) + const rows = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); + console.log('All rows:', rows); + const students = rows.slice(1).map(row => ({ + id: row[0], + name: row[1], + points: parseFloat(row[2]) || 0 + })); + + console.log('Parsed students:', students); + + // 插入数据到数据库 + const result = await db.collection('students').add({ + data: students + }); + + console.log('Students inserted into database:', result); + + // 立即查询数据库,确保数据已经正确插入 + const queryResult = await db.collection('students').get(); + console.log('Query result after insertion:', queryResult); + + return { success: true, message: 'Students imported successfully' }; + } catch (error) { + console.error('Error importing students:', error); + return { success: false, message: 'Error importing students' }; + } +}; \ No newline at end of file