项目实战网站后台VUE导入Excel并读取数据保存到数据库+.NET WebApi接口

前端:VUE

 

复制代码
<template>
    <div v-loading="loading" element-loading-text="Loading...">
        <el-header class="order">
            <el-row class="top from" :gutter="20">
                <el-col :span="15">
                    <el-col class="datatime">
                        <el-cascader
                              v-model="value"
                              :options="options"
                              @change="changeDatatime"
                            ></el-cascader>
                    </el-col>
                    <el-col :span="19">
                        <el-date-picker class="time" v-model="param.startTime" type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期时间" @change="changeTime">
                        </el-date-picker><el-date-picker class="time" v-model="param.endTime" type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期时间" @change="changeTime">
                        </el-date-picker>
                    </el-col>
                </el-col>
                <el-col :span="9" class="function">
                    <div class="upload-excel">
                    <input
                      ref="excel-upload-input"
                      class="excel-upload-input"
                      type="file"
                      accept=".xlsx, .xls"
                      @change="selectFile"
                    >
                    </div>
                    <el-button type="primary" @click="downloadExcel()">下载导入模板</el-button>
                    <el-button type="primary" @click="uploadExcel()">导入</el-button>
                    <el-button @click="refresh()">刷新</el-button>
                </el-col>
            </el-row>

            <div class="radio">
                <div class="state">
                    <span class="title">状态:</span>
                    <el-radio-group v-model="param.state" @change="changeState">
                        <el-radio label="-1">全部</el-radio>
                        <el-radio label="0">未验铅</el-radio>
                        <el-radio label="1">已验铅</el-radio>
                    </el-radio-group>
                </div>
            </div>

            <div class="btn">
                <div class="material">
                    封号:
                    <el-input placeholder="铅封号" size="small" v-model="param.sealNo" @input="changeCustom"></el-input>
                </div>
                <div class="custom" v-if="userIsShow">
                    承运商:
                    <el-input placeholder="承运商" size="small" v-model="param.carrierName" @input="changeCustom">
                        <template #suffix>
                            <i class="el-input__icon el-icon-search hand" @click="openCustom(4)"></i>
                        </template>
                    </el-input>
                </div>
            </div>
        </el-header>
        <el-main>
            <el-table :data="dataList" :header-cell-style="{background:'#F4F8FF'}" row-key="Id"
                :tree-props="{children: 'MaterialList', hasChildren: 'hasChildren'}" class="treeTable" @select="changeSelection" @select-all="changeSelectionAll">
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column prop="Id" label="ID" type="" width="100">
                </el-table-column>
                <el-table-column prop="DeparturePort" label="起运港" type="" width="100">
                </el-table-column>
                <el-table-column prop="DestinationPort" label="目的港" type="" min-width="100" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="BoxType" label="箱型" min-width="100" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="ShipName" label="船名/航次" width="180" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="BookingNumber" label="订舱单号"  width="180">
                </el-table-column>
                <el-table-column prop="CntrNo" label="柜号" width="150">
                </el-table-column>
                <el-table-column prop="SealNo" label="封号" width="110" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="ProductName" label="品名" width="110">
                </el-table-column>
                <el-table-column prop="Tonnage" label="装箱吨数" width="100" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="Barge" label="驳船" width="150" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="SampleNumber" label="样号" width="150" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="CarrierName" label="承运商" width="150" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="Remark" label="备注" width="110" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="State" label="状态" width="100">
                    <template #default="scope">
                        <span class="errorColor" v-if="scope.row.State==0">未验铅</span>
                        <span class="linkColor"  v-else-if="scope.row.State==1">已验铅</span>
                    </template>
                </el-table-column>
                <el-table-column prop="SaveTime" label="保存时间" width="170">
                </el-table-column>
            </el-table>
            <div class="page clearFloat">
                <span class="currentData">当前共
                    <span class="dataNum">{{dataTotal}}</span> 条记录</span>
                <el-pagination background layout="prev, pager, next,sizes,jumper" :total="dataTotal" @size-change="handleSizeChange"
                 @current-change="handleCurrentChange" :page-sizes="[10, 20, 30, 40]">
                </el-pagination>
            </div>
        </el-main>
    </div>
    
    <el-dialog title="物料" v-model="materialShow" :destroy-on-close="true" :close-on-click-modal="false">
        <material-choose @material-choose="currentMaterial"></material-choose>
    </el-dialog>
    <el-dialog title="单位" v-model="customShow" :destroy-on-close="true" :close-on-click-modal="false">
        <custom-choose @custom-choose="currentCustom"></custom-choose>
    </el-dialog>
    <el-dialog title="车辆" v-model="vehicleShow" custom-class="headerDialog" :destroy-on-close="true" :close-on-click-modal="false">
        <vehicle-choose @vehicle-choose="currentVehicle"></vehicle-choose>
    </el-dialog>
    <el-dialog title="司机" v-model="driverShow" custom-class="headerDialog" :destroy-on-close="true" :close-on-click-modal="false">
        <driver-choose @driver-choose="currentDriver"></driver-choose>
    </el-dialog>
    
</template>

<script>
    import axios from 'axios';
    import customChoose from "@/components/BasicData/Custom"
    export default {
        inject: ['reload'],
        components:{
            "custom-choose":customChoose
        },
        data() {
            return {
                loading:false,

                param: {
                    organCode:'',
                    pageIndex: 1,
                    pageSize: 10,
                    state: '-1',
                    startTime: '',
                    endTime: '',
                    sealNo: '',
                    carrierCode:'',
                    carrierName:'',
                },
                time: [],
                dataList: [],
                dataTotal: 0,
                options: [{
                        value: '1',
                        label: '当日'
                    }, {
                        value: '2',
                        label: '当月'
                    }, {
                        value: '3',
                        label: '一周'
                    }, {
                        value: '4',
                        label: '一月'
                    }, {
                        value: '5',
                        label: '三月'
                    },
                    {
                        value: '6',
                        label: '半年'
                    },
                    {
                        value: '7',
                        label: '一年'
                    }
                ],
                value: '',
                codearr:[],
                organCode:'',
                userIsShow:true,
                userInfo:{},
                customNature: 1,
                customShow:false
                
            }
        },
        created() { //创建后挂载
            
        },
        mounted() {
            this.organCode=this.$store.state.OrganCode;
            this.param.organCode=this.$store.state.OrganCode;
            this.userInfo= this.$store.state.userInfo
            if(this.userInfo.UserIdentifier==7){
                this.userIsShow=false;
            }
            this.setDefault()
            this.getList()
        },
        methods: {
            async downloadExcel() {
                window.open(axios.defaults.baseURL+'/UpLoad/ExcelToTable/发货单模板.xlsx', '_blank');
                toastr.info("模板下载中...");
            },
            //上传
            uploadExcel() {        
                let that = this;
                console.log(that.userIsShow)
                console.log(that.param.carrierCode)
                if(that.userIsShow)
                {
                    if(that.param.carrierCode=='')
                    {
                        that.$message({
                            message: '请选择承运商!',
                        });
                        return;
                    }
                }
                
                this.$refs['excel-upload-input'].click()
            },
            // 点击文件选择-------------------------------
            selectFile(e) {                
              // 获取选择的文件列表
              const files = e.target.files
              if (files.length > 0) {
                this.uploadFiles(files[0])
              }
            },
            // 选择了文件后上传的方法,两处都用到了,所以封装了方法
            async uploadFiles(file) {
                let that = this;
                that.loading = true
                const formData = new FormData();
                formData.append('file', file);
                formData.append('code', that.param.carrierCode);
                formData.append('name', that.param.carrierName);
                
                that.$axios.DeliveryDetails.UploadExcel(formData).then(res => {
                    that.loading = false
                    if (res.errCode == 0) {
                        that.$message({
                            message: '上传成功!',
                        });
                    } else {
                        that.$message.error(res.errMsg);
                    }
                }).catch(err => {
                    that.loading = false
                    that.$message.error(err.errMsg);
                })
                
                this.reload()
            },

            refresh() {
                this.reload()
            },
            changeSelection(selection,row){
                this.codearr = selection
            },
            changeSelectionAll(selection){
                this.codearr = selection
            },
            changeDatatime(value) {
                let that = this;
                this.param.startTime = that.$base.getStartTime(value);
                this.param.endTime = that.$base.getDateNow() + " 23:59:59";
                that.getList();
            },
            setDefault() {
                var that = this;
                that.value = "2";
                this.param.startTime = that.$base.getStartTime(that.value);
                this.param.endTime = that.$base.getDateNow() + " 23:59:59";
            },

            getList() {
                let that = this;
                that.loading = true
                that.$axios.DeliveryDetails.GetList(that.param).then(res => {
                    that.loading = false
                    if (res.errCode == 0) {
                        that.dataList = res.result
                        that.dataTotal=res.totalCount
                    } else {
                        that.$message.error(res.errMsg);
                    }
                }).catch(err => {
                    that.loading = false
                    that.$message.error(err.errMsg);
                })
            },
            handleSizeChange(pageSize) {
                this.param.pageSize = pageSize
                this.getList()
            },
            handleCurrentChange(pageIndex) {
                this.param.pageIndex = pageIndex
                this.getList()
            },

            changeTime(val) {
                this.getList()
            },

            changeState(val) {
                this.getList()
            },
            changeCustom() {
                this.getList()
            },
            openCustom(nature) {
                this.customNature = nature
                this.customShow = true
            },
            currentCustom(row) {
                this.param.carrierCode = row.ThirdCode
                this.param.carrierName = row.Name
                this.customShow = false
                this.getList()
            },
        }
    }
</script>

<style scoped="scoped" lang="less">
    .el-header {
        padding: 24px;
        height: auto !important;
        .datatime {
            width: 90px !important;
            flex: 0 0 90px !important;
            padding-left: 0 !important;
        }
        .function {
            text-align: right;
        }

        .title {
            width: 42px;
            display: inline-block;
        }

        .type {
            margin-top: 12px;
            font-size: 14px;
            color: #595959;
            line-height: 22px;

            .el-checkbox-group {
                display: inline-block;
            }
        }

        .radio {
            width: 100%;
            font-size: 14px;
            color: #595959;
            line-height: 22px !important;
            height: 22px !important;
            margin-top: 15px;

            .state,
            .audit {
                display: inline-block;
            }

            .audit {
                margin-left: 12px;
            }
        }

        .btn {
            margin-top: 15px;

            .custom,
            .material {
                display: inline-block;

                .el-input {
                    margin-left: 8px;
                    width: 219px !important;
                }
                margin-right: 24px;
            }

            .material {
                
            }
        }

    }

    .el-main {
        padding-top: 0px;


    }

    .tree {
        margin-right: 12px;
        border: 1px solid #F4F8FF;
    }

    .topSpan {
        box-sizing: border-box;
        display: inline-block;
        width: 100%;
        height: 44px;
        line-height: 44px;
        background-color: #F4F8FF;
        padding-left: 28px;
        font-size: 14px;
    }
    
     .excel-upload-input {
        display: none;
        z-index: -9999;
      }
</style>
复制代码

 

后端:WebApi

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/// <summary>
/// 导入Excel
/// </summary>
/// <returns></returns>
[HttpPost]
public ApiResponse UploadExcel()
{
    try
    {
        HttpContextBase httpContextBase = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
        HttpRequestBase httpRequestBase = httpContextBase.Request;//定义传统request对象
        HttpFileCollectionBase files = httpRequestBase.Files;
        string name = httpRequestBase.Form["name"];
        string code = httpRequestBase.Form["code"];
        if (files != null && files.Count > 0)
        {
            string fullUpLoadPath = HttpContext.Current.Server.MapPath("~/UpLoad/ExcelToTable/");
            //检查本地上传的物理路径是否存在,不存在则创建
            if (!System.IO.Directory.Exists(fullUpLoadPath))
            {
                System.IO.Directory.CreateDirectory(fullUpLoadPath);
            }
 
            string fileSuffix = Path.GetExtension(files[0].FileName).ToLower();
            string fileId = Guid.NewGuid().ToString();
            string dateKey = DateTime.Now.ToString("yyyyMMddHHmmss");
            string fileName = fullUpLoadPath + dateKey + fileSuffix;
 
            if (fileSuffix!= ".xlsx" && fileSuffix != ".xls")
            {
                throw new Exception("请选择正确的格式文件");
            }
 
            files[0].SaveAs(fileName);
 
 
            List<DeliveryDetailsVO> list  =  Tools.ExcelToData(fileName);
            foreach (var item in list)
            {
                item.State = 0;
                item.UserCode = loginUserInfo.UserCode;
                item.UserName = loginUserInfo.UserName;
                item.SaveTime = Tools.Now;
                item.OrganCode = loginUserInfo.OrganCode;
                if (!string.IsNullOrEmpty(code))
                {
                    item.CarrierCode = code;
                    item.CarrierName = name;
                }
                else
                {
                    var customTemp = customServices.GetCustomByUserCode(loginUserInfo.OrganCode, loginUserInfo.UserCode);
                    if (customTemp != null)
                    {
                        item.CarrierCode = customTemp.ThirdCode;
                        item.CarrierName = customTemp.Name;
                    }
                }
 
 
                string whereStr = $" and SealNo='{item.SealNo}'";
                var deliveryDetailsTemp = deliveryDetailsServices.GetList(loginUserInfo.OrganCode, whereStr);
                if (deliveryDetailsTemp.Count > 0)
                    continue;
 
                deliveryDetailsServices.SaveEntity(item);
            }
        }
        else
        {
            throw new Exception("请选择要上传的文件");
        }
 
        return BaseApiResponse.ApiSuccess();
    }
    catch (Exception ex)
    {
        return BaseApiResponse.ApiError(ex.Message);
    }
}

  

posted @   上位机李工  阅读(61)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示