From 2a892d2ab8fcbd3fda8febb3097fc3cf2d2457c5 Mon Sep 17 00:00:00 2001 From: pg78ac9nr <2401677463@qq.com> Date: Thu, 10 Oct 2024 12:27:48 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BA=91=E5=87=BD=E6=95=B01?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 2.0 cloud index.js | 52 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 2.0 cloud index.js diff --git a/2.0 cloud index.js b/2.0 cloud index.js new file mode 100644 index 0000000..dbde63d --- /dev/null +++ b/2.0 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