vue+express+mysql(3)增删改查,导入导出excel

一.Vue前端项目
vue+express+mysql(3)增删改查,导入导出excel_第1张图片

1.vue.config.js配置代理跨域

module.exports={
     
    devServer: {
     
        proxy: {
     
          //配置跨域
          '/api': {
     
            target: 'http://127.0.0.1:3000/',
            ws: true,
            changOrigin: true,
            pathRewrite: {
     
              '^/api': 'api'
            },
            open: true /*启动项目自动打开浏览器(同时需在package.json中配置:"scripts": {
    "dev": "vue-cli-service serve --open",}*/
          }
        }

    }
}

2.headers/headers.js

import $md5 from 'js-md5'

export function getHeader(url,code){
     
    //时间戳
    let timestamp=Date.now()
    let token=sessionStorage.getItem('user-token')===null?'':sessionStorage.getItem('user-token')
    let source='web'
    let sign=$md5(source+url+code+timestamp+token)
    
    return {
     'Content-type':'application/json;charset=UTF-8','token':token,
    'timestamp':timestamp,'code':code,'sign':sign,'source':source
}
}

3.axios/request.js

import axios from 'axios'
import {
     getHeader} from '@/headers/header'
import {
     Message,MessageBox} from 'element-ui'

let baseURL='/'
//创建axios实例

const service=axios.create({
     
    baseURL:baseURL,
    timeout:30000 //请求超时时间
})

//request拦截器
service.interceptors.request.use(
    config=>{
     
    let url=config.url.replace(config.baseURL,'')
    let code=config.code;
    config.headers=getHeader(url,code)//让每个请求携带自定义签名
    return config
},
 error=>{
     
     Promise.reject(error)
   
 }
)

//response拦截器

service.interceptors.response.use(
    response=>{
     
        
    if(response.config.responseType=='blob')  {
       
        if(response.status==200){
     
            return response
        }else {
     
            return Promise.reject('error')
        }
    }else{
     
      const res=response.data;
      if(res.code===200){
     
          return response.data
      }else if(res.code===407){
     
        //   console.log('token失效跳转登录页面')
        // sessionStorage.clear();
        // location.href=''
      }else{
     
          Message({
     
              message:res.message,
              type:'error',
              duration:5*1000
          })
          return Promise.reject('error')
      }
    }
   },
   error=>{
     
       Message({
     
           message:error.message,
           type:'error',
           duration:5*1000
       })
      
       return Promise.reject(error)
   }
)

export default service

4.axios/api.js

import request from './request'

export function getList(data){
     
    return request({
     
        url:'/api/index',
        method:'post',
        data,
        
    })
}

export function insertForm(data){
     
    return request({
     
        url:'/api/insert',
        method:'post',
        data,
    })
}
export function updateForm(params){
     
     return request({
     
         url:'/api/update',
         method:'get',
         params
     })
}
export function deletelist(data){
     
    return request({
     
        url:'/api/delete',
        method:'delete',
        data
    })
}

export function importFile(data){
     
   return request({
     
        url:'/api/import',
        method:'post',
        data
    })
}

export function exportFile(data){
     
    return request({
     
        url:'/api/export',
        method:'post',
        data,
        responseType:'blob'
    })
}
export function pageQuery(params){
     
    return request({
     
        url:'/api/pageQuery',
        method:'get',
        params
    })
}

3.views/about.vue

<template>
    <div>
<!-- Form -->

<el-button type='primary' @click="findList">查询</el-button>
<el-button type="primary" @click="dialogForm" >新增</el-button>
<el-button type="primary" @click="dialogUpdate">修改</el-button>
<el-button type="danger" @click="deletelist">删除</el-button>
<el-button type="primary" @click="importExcel">导入</el-button>
<el-button type="primary" @click="exportExcel">导出</el-button>
 <el-dialog :visible.sync='dialogImport'>
  <el-upload
  class="upload-demo"
  action=""
  :auto-upload='false'
  :http-request='uploadFile'
  :on-change="handleChange"
  ref='importInfo'
  :show-file-list='isShow'
  >
  <el-input slot='trigger' v-model='importfilename' style='width:260px' placeholder="请选择文件"/>
  <el-button size="small" style='margin-left:20px' type="primary" @click='sumbitFile'>上传文件</el-button>
</el-upload>
 </el-dialog>


 <el-table
    :data="tableData"
    @selection-change="handleSelectionChange"
    style="width: 100%">
    <el-table-column
      type="selection"
      label="序号"
      prop='id'
      >
    </el-table-column>
    <el-table-column
      prop="userName"
      label="用户名"
      width="180">
    </el-table-column>
    <el-table-column
      prop="passWord"
      label="密码"
      width="180">
    </el-table-column>
    <el-table-column
      prop="realName"
      label="真实姓名">
    </el-table-column>
  </el-table>
<!-- 新增或修改弹出框 -->
<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
  <el-form :model="form" ref='insertform'>
    <el-form-item label="用户名" :label-width="formLabelWidth" prop="userName">
      <el-input v-model="form.userName" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="密码" :label-width="formLabelWidth" prop='passWord'>
      <el-input v-model="form.passWord" autocomplete="off"></el-input>
    </el-form-item>
     <el-form-item label="真实姓名" :label-width="formLabelWidth" prop='realName'>
      <el-input v-model="form.realName" autocomplete="off"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="cancel">取 消</el-button>
    <el-button type="primary" @click="dialogStatus==='create'?insert():update()" >确 定</el-button>
  </div>
</el-dialog>
<!-- 分页查询 -->
  <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageInfo.currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageInfo.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total"
      v-show='pageInfo.total>0'
      >
    </el-pagination>
    </div>
</template>
<script>
import {
     insertForm,getList,deletelist,updateForm,importFile,exportFile,pageQuery} from '../axios/api'
import {
     Message} from 'element-ui'
  export default {
     
    data() {
     
      return {
     
        dialogTableVisible: false,
        dialogFormVisible: false,
        dialogStatus:'',
        dialogImport:false,
        textMap:{
     
            create:'新增',
            update:'修改'
        },
        form: {
     
          id:'',
          userName: '',
          passWord:'',
          realName:""
        },
        tableData:[],
        formLabelWidth: '120px',
        selected:[],
        importfilename:'',
        isShow:false,
     
       //分页
       pageInfo:{
     
       currentPage:1,
       limit:10,
       total:0,
       }
       
      };


    },
  methods:{
     
    //每页条目改变时触发
      handleSizeChange(val){
     
        this.pageInfo.limit=val
        this.findList()
      },
      //当前页改变时触发
      handleCurrentChange(val){
     
       this.pageInfo.currentPage=val
       this.findList()
      },
      handleSelectionChange(val){
     
       this.selected=val
      },
      dialogForm(){
     
          this.dialogFormVisible=true
          this.dialogStatus='create'
          this.$nextTick(()=>{
     
          this.$refs['insertform'].resetFields()
          })
          },    
       dialogUpdate(){
     
          this.dialogStatus='update'
          const selectedList=this.selected
          if(selectedList.length===0){
     
             Message({
     
              message:'请选择要修改的数据',
              type:'error',
              duration:1000
              })
             return
            }else if(selectedList.length>1){
     
              Message({
     
              message:'一次只能选择一条数据',
              type:'error',
              duration:1000
              }) 
               return 
            }
          this.dialogFormVisible=true
          this.form={
     
              id:this.selected[0].id,
              userName:this.selected[0].userName,
              passWord:this.selected[0].passWord,
              realName:this.selected[0].realName
          }
       }, 

       cancel(){
     
         this.dialogFormVisible=false
         this.$refs['insertform'].resetFields()
       },
    //分页查询
  findList(){
     
       const data={
     
         currentPage:this.pageInfo.currentPage,
         pageSize:this.pageInfo.limit
       }
       pageQuery(data).then(res=>{
     
       this.tableData=res.data
       this.pageInfo.total=res.total
      //  let pages=this.pageInfo.total/this.pageInfo.limit

       console.log(pages,456)
       console.log(this.tableData)
       }).catch(error=>{
     
           console.log(error)
       })
      },
   insert(){
     
       const data=this.form
       insertForm(data).then(res=>{
     
        this.findList()
        this.dialogFormVisible=false
       }).catch(error=>{
     
           console.log(error)
       }) 
   },

//update
update(){
     
   const selectId=this.form
   console.log(selectId,222)
   updateForm(selectId).then(res=>{
     
       this.dialogFormVisible=false
       this.findList()
       console.log(res)
   }).catch(error=>{
     
       console.log(error)
   })

},
   //删除

  deletelist(){
     
      const selectedList=this.selected
       console.log(selectedList,'55555')
   const data=[]
   if(selectedList.length===0){
     
    Message({
     
         message:'请选择要删除的数据',
              type:'error',
              duration:5*1000
    })
    return
   }
   for(let i=0;i<selectedList.length;i++){
     
       console.log(selectedList[i])
       data.push({
     id:selectedList[i].id})
   }
   console.log(data)
   const params={
     list:data}
//    const arr=[]
//    arr.push(params)
   deletelist(params).then(res=>{
     
       this.findList()
   }).catch(error=>{
     
       console.log(error)
   })
  },
   importExcel(){
     
     this.dialogImport=true
     this.importfilename=''
     this.isShow=false
     this.$nextTick(()=>{
     
     this.$refs.importInfo.clearFiles()
     })
     
  },
   handleChange(File){
     
       let xls=File.name.split('.')
       
       if(xls[1]==='et'||xls[1]==='xls'||xls[1]==='xlsx'){
     
         this.isShow=true
         this.importfilename=File.name
       }else {
     
           Message({
     
               message:'上传的文件只能是excel文件',
               type:'error'
           })
           this.isShow=false
           this.importfilename=''
           this.$refs.importInfo.clearFiles()
       }
        // this.importfilename=''
        // this.isShow=false
        // this.importfilename=File.name
   },
   sumbitFile(){
     
    if(this.importfilename===''){
     
        Message({
     
            message:'请选择上传文件',
            type:'warning'
        })
    }else {
     
        this.$refs.importInfo.submit()
        this.dialogImport=false
    }
   },
   uploadFile(file){
     
       const formData=new FormData()
       formData.append('importFile',file.file)
      importFile(formData).then(res=>{
     
          this.dialogImport=false   
          this.findList()
      }).catch(error=>{
     
      })
   },
   exportExcel(){
     
       console.log(this.form,'导出')
       const data=this.form
      exportFile(data).then(response=>{
     
          console.log(response)
          const blob=new Blob([response.data],{
     type:'application/vnd.ms-excel'})
          const fileStr=response.headers['content-disposition'].split(';')[1]
          const fileName=fileStr.split('filename=')[1]
          var url=window.URL.createObjectURL(blob)
          var link=document.createElement('a')
          link.href=url;
          link.download=decodeURI(fileName)
          link.click()
      }).catch(error=>{
     
          console.log(error)
      })
   }
  }
  };
</script>

二.express后端项目
vue+express+mysql(3)增删改查,导入导出excel_第2张图片
1.db/mysql.js


var connection=({
     
    host:'127.0.0.1',
    port:'3306',
    user:'root',
    password:'123456',
    database:'cmecuser'
})
module.exports=connection```
2.db/sqlMap.js

```javascript
var mysql=require('mysql')

var $mysql=require('./mysql')
var connectSql=mysql.createConnection($mysql)


connectSql.connect()
module.exports={
     
  find:function(sql,params,callback){
     
     connectSql.query(sql,params,callback)
  },
   
  insert:function(sql,params,callback){
     
    // connectSql.query(sql,params,function(error,result){
     
    //   if(error){
     
    //     throw error
    //   }
    // callback(result)
    // }) //这样写能新增,但总是返回错误信息
      connectSql.query(sql,params,callback)
  } ,
  update:function(sql,params,callback){
     
    // connectSql.query(sql,params,function(error,result){
     
    //  if(error){
     
    //    throw error
    //  }
    //  callback(result)
    // })
    connectSql.query(sql,params,callback)
  },

  delete:function(sql,params,callback){
     
    // connectSql.query(sql,params,function(error,result){
     
    //   if(error){
     
    //     throw error
    //   }
    //   callback(result)
    // })
    connectSql.query(sql,params,callback)
  }
}

3.routers/index.js

var express = require('express');
var router = express.Router();

var multiparty = require('multiparty');
var xlsx = require('node-xlsx');
var fs=require('fs')
var stream=require('stream')
// var mysql=require('mysql')
// var $mysql=require('../db/mysql')
// var connectSql=mysql.createConnection($mysql)
// connectSql.connect()
const {
     createExcel} = require('./utils');
var connectSql=require('../db/sqlMap');
const {
      type } = require('os');
var sql='SELECT * FROM user'
router.post('/api/index', function(req, res, next) {
     
  connectSql.find(sql,function(error,result){
     
    if(error){
     
     return res.json({
     code:0})
    }
    const data = {
     
      code: 200,
      data: result,
      isSuccess: true,
      msg: "请求成功"
    }
   return res.json(data)
  })
});

router.post('/api/insert',function(req,res,next){
     
  const params=req.body
  console.log(req.body)
  const addsql='INSERT INTO user(userName,passWord,realName) VALUES(?,?,?)';
  const add_value=[params.userName,params.passWord,params.realName]
  connectSql.insert(addsql,add_value,function(error,result){
     
   if(error){
     
      console.log(req.body,'111111')
       return res.json({
     
        code: 1,
        message: "新增失败",
      });

    }
    console.log(req.body,'5555555')
    const data={
     
      code:200,
      msg:'新增成功',
      result:result,
      isSuccess: true
    } 
    return res.json(data)
    
  })
})

//修改
router.get('/api/update',function(req,res,next){
     
  const params=req.query
  console.log(params,'17894332255')
  const updateSql='update user set userName=?,passWord=?,realName=? where id=?'
  const update_value=[params.userName,params.passWord,params.realName,params.id]
  connectSql.update(updateSql,update_value,function(error,result){
     
    if(error){
     
      return res.json({
     
        code:1,
        msg:'修改失败'
      })
    }
    const updateData={
     
      code:200,
      msg:'修改成功',
      data:result
    }
   return res.json(updateData)
  })
})

//删除

router.delete('/api/delete',function(req,res,next){
     
  const params=req.body.list
  const arr=params.map(item=>{
     
    return item.id
  })
//拼接字符串方式1
  // var str=''
  // var kk=''
  // for(let i=0;i
  //    kk+='"'+arr[i]+'",'
  // }
  // str=kk.substring(0, kk.lastIndexOf(","))
  // const deleteSql = "delete from user where id in(" + str + ")";
//拼接字符串方式2  
  const string=arr.toString()
  const deleteSql = "delete from user where id in(" + string + ")";

console.log(string,'9999')
  connectSql.delete(deleteSql,function(error,result){
     
    if(error){
     
      return res.json({
     
        code:1,
        msg:'删除失败'
      })
    }
    return res.json({
     
      data:result,
      code:200,
      msg:'删除成功'
    })
  })

})

//导入
router.post('/api/import',function(req,res,next){
     
  console.log(req.body,"body")
  let form = new multiparty.Form();
  var orr=1
  form.parse(req, function(err,fields,file){
     
    var path=file.importFile[0].path
    var obj = xlsx.parse(path);
    var excelObj=obj[0].data;
    console.log(excelObj,'555555')
    for(let i=1;i<excelObj.length;i++){
     
       console.log(excelObj[i],'1111111111111111111')
       const addsql='INSERT INTO user(userName,passWord,realName) VALUES('+`${
       excelObj[i]}`+')';
       connectSql.insert(addsql,function(error,result){
     
        if(error){
     
          console.log(error,'22222222');
           orr=0
         }else{
     
           orr=1
         }
       })
    }
    if(orr){
     
      res.json({
     "result":{
     message:"文件上传成功!"},code:200});
    }else{
     
    	res.json({
     "result":{
     message:"文件上传失败!"}});
    }
  });
},
)

  //导出测试
  router.post('/api/exportTest', function(req, res, next) {
     
      const options={
     
        '!cols':[
          {
     wch:100},
          {
     wch:45},
        ]
      };
  let xlsxObj=[{
     
    name:'sheet',
    data:[
            ['姓名', '年龄'],
            ['王五', 18],
            ['刘六', 18]
    ]
  }]
let exportExcel=xlsx.build(xlsxObj,options)
 console.log(exportExcel,'67894buffer')
 res.set({
     
  "Content-Type":'application/vnd.openxmlformats;charset=utf-8',
  "Content-Disposition": "attachment; filename=" + encodeURIComponent("食物商品信息") + ".xlsx"
});

res.end(exportExcel,'binary');
  });

router.post('/api/export',function(req,res,next){
     
 //默认查询下载所有数据
   connectSql.find(sql,function(error,result){
     
     if(error){
     
       return res.json(error)
     }
    
    var arr=[['序号','用户名','密码','真实姓名']]
    result.forEach(item=>{
     
      let arr1=[]
      arr1.push(item.id,item.userName,item.passWord,item.realName)
      arr.push(arr1)
    })

    let xlsxObj=[{
     
      name:'sheet',
      data:arr
    }]
   
   const filename='用户信息表'
   let Excel=xlsx.build(xlsxObj)
   res.set({
     
    "Content-Type":'application/vnd.openxmlformats;charset=utf-8',
    "Content-Disposition": "attachment; filename=" + encodeURIComponent(filename) + ".xlsx"
  });
  res.end(Excel,'binary');
   })

})

//分页查询

router.get('/api/pageQuery',function(req,res,next){
     
   let currPage=req.query.currentPage
   let pageSize=req.query.pageSize
   console.log(req.query)
   let start = (currPage - 1) * pageSize
   let sqlParam = [start, pageSize-0]
   let total
   let pages
  const pageSql='select * from user limit ?,?';
  let sqlCount = "select count(*) from user";
   connectSql.find(sqlCount,function(error,result){
     
     total = result[0]["count(*)"]
    //  pages=Math.ceil(total/pageSize)
   })
   connectSql.find(pageSql,sqlParam,function(error,result){
     
     if(error){
     
       return res.json({
     
         code:1,
         msg:'查询失败'
       })
     }
   
     return res.json({
     
       total:total,
       code:200,
       data:result,
     })
    
   })
})
  
module.exports = router;

你可能感兴趣的:(vue+express+mysql(3)增删改查,导入导出excel)