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' }; } };