zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    软件测试经理工作职责
    测试经理的年终总结
    从0到1,如何快速搭建人才梯队?
    Centos 的常用命令总结
    Docker的常用命令总结
    Jenkins Android项目编译配置(完整版)
    linux CentOS 权限问题修复(chmod 777 -R 或者chmod 755 -R问题修复)
    基于gitlab的项目管理流程
    js 防抖动、重复提交、频繁点击
    GPUImage移植总结
  • 原文地址:https://www.cnblogs.com/ashion89/p/12715299.html
Copyright © 2011-2022 走看看