node 读取excel表格中数据,批量插入数据库

引入依赖 

   const xlsx=require('xlsx')
 1 async function readExcel(filepath){
 2     //读取内容
 3     const workbook = xlsx.readFile(filepath);
 4     const sheetNames = workbook.SheetNames; //获取表名
 5     const sheet = workbook.Sheets[sheetNames[0]]; //通过表名得到表对象
 6     const thead = [sheet.A1.v, sheet.B1.v];
 7     const data = xlsx.utils.sheet_to_json(sheet); //通过工具将表对象的数据读出来并转成json
 8     const theadRule = ['学号', '姓名'];
 9     const isValid = thead.every((value, index) => value === theadRule[index]); //检验表字段
10     if(!isValid) {
11         return false
12     }
13 
14     let params = [];
15     for (let i = 0; i < data.length; i++) {
16         let  edu_student_number=data[i][thead[0]];
17         let  name= data[i][thead[1]];    
18         params.push({
19                 edu_student_number:data[i][thead[0]],           
20                 name: data[i][thead[1]]       
21             });
22     }
24     //数据批量插入数据库
25     let sql='INSERT INTO student_table (edu_student_number,name) VALUES ?';
26     const values = [];
27     params.forEach(function(item) {
28         const arr = [];
29         for(const field in item) {
30             arr.push(item[field]);
31         }
32         values.push(arr);
33     });
34     try{
35           await sql_execute(sql,[values])
return true
36 }catch(e){ 37 return false 38 } 42 } 43 44 //sql执行
   const pool = mysql.createPool({})
45 function sql_execute(sql,params) {
46     return new Promise(function (resolve, reject) {
47         pool.query(sql,params, function (error, results,fields) {
48             if (error) {
49                 return reject(error);
50             } else {
51                 resolve({results,fields});
52             }
53         })
54     })
55 }

 

posted @ 2020-04-17 09:24  打工的工人  阅读(782)  评论(0编辑  收藏  举报