ソースを参照

增加物料价格表的价格导入功能

austin 3 ヶ月 前
コミット
e1ee0be4fe

+ 22 - 0
JLHHJSvr/Com/ImportMtrlPriceByExcel.cs

@@ -0,0 +1,22 @@
+using LJLib.Net.SPI.Com;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace JLHHJSvr.Com
+{
+    public class ImportMtrlPriceByExcelRequest : ILJRequest<ImportMtrlPriceByExcelResponse>
+    {
+        public string token { get; set; }
+        public string base64 { get; set; }
+        public byte[] filedata { get; set; }
+        public string filename { get; set; }
+        public override string GetApiName()
+        {
+            return "ImportMtrlPriceByExcel";
+        }
+    }
+    public class ImportMtrlPriceByExcelResponse : LJResponse { }
+}

+ 1 - 1
JLHHJSvr/Com/Model/u_mtrl_price_pricelist.cs

@@ -6,7 +6,7 @@ using System.Text;
 
 namespace JLHHJSvr.Com.Model
 {
-    [PK(new[] { "mtrlid", "pricelistid" })]
+    [PK(new[] { "mtrlid", "pricelistid", "mtrlid,pricelistid" })]
     public sealed class u_mtrl_price_pricelist
     {
         /// <summary>

+ 209 - 0
JLHHJSvr/Excutor/ImportMtrlPriceByExcelExcutor.cs

@@ -0,0 +1,209 @@
+using JLHHJSvr.BLL;
+using JLHHJSvr.Com;
+using JLHHJSvr.Com.Model;
+using JLHHJSvr.LJException;
+using LJLib.DAL.SQL;
+using LJLib.Net.SPI.Server;
+using NPOI.HSSF.UserModel;
+using NPOI.HSSF.Util;
+using NPOI.SS.UserModel;
+using NPOI.XSSF.UserModel;
+using System;
+using System.Collections.Generic;
+using System.Data.SqlClient;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace JLHHJSvr.Excutor
+{
+    internal sealed class ImportMtrlPriceByExcelExcutor : ExcutorBase<ImportMtrlPriceByExcelRequest, ImportMtrlPriceByExcelResponse>
+    {
+        protected override void ExcuteInternal(ImportMtrlPriceByExcelRequest request, object state, ImportMtrlPriceByExcelResponse rslt)
+        {
+            var tokendata = BllHelper.GetToken(request.token);
+            if (tokendata == null)
+            {
+                throw new LJCommonException("会话已经中断");
+            }
+
+            using (var con = new SqlConnection(GlobalVar.ConnectionString))
+            using (var cmd = con.CreateCommand())
+            {
+                con.Open();
+                if (!string.IsNullOrEmpty(request.base64))
+                {
+                    var typeEndIndex = request.base64.IndexOf(";base64", StringComparison.Ordinal);
+                    if (typeEndIndex <= 0)
+                    {
+                        rslt.ErrMsg = "格式异常,请重新上传";
+                        return;
+                    }
+                    request.filedata = Convert.FromBase64String(request.base64.Substring(typeEndIndex + 8));
+
+                }
+                if (request.filedata == null || request.filedata.Length == 0)
+                {
+                    throw new LJCommonException("excel文件不能为空");
+                }
+                IWorkbook workbook = null;
+                using (var ms = new MemoryStream(request.filedata))
+                {
+                    if (request.filename.ToLower().IndexOf(".xlsx") > 0)
+                    {
+                        workbook = new XSSFWorkbook(ms);
+                    }
+                    else if (request.filename.ToLower().IndexOf(".xls") > 0)
+                    {
+                        workbook = new HSSFWorkbook(ms);
+                    }
+                    else
+                    {
+                        throw new LJCommonException("只支持excel类型文件");
+                    }
+                }
+                var sheet = workbook.GetSheetAt(0); //获取第一个工作表
+                if (sheet.LastRowNum <= 0)
+                {
+                    throw new Exception("该表没有数据");
+                }
+                IRow row;
+                row = sheet.GetRow(0);
+                if (row == null)
+                {
+                    throw new Exception("没有数据");
+                }
+
+                IRow headerRow = sheet.GetRow(0);
+                List<HeaderPropetry> headers = new List<HeaderPropetry>();
+                List<HeaderPropetry> priceHeaders = new List<HeaderPropetry>();
+                int k = 0;
+                foreach (ICell cell in headerRow.Cells)
+                {
+                    k++;
+                    if(cell.ToString() == "类别" || cell.ToString() == "名称")
+                    {
+                        headers.Add(new HeaderPropetry { name = cell.ToString(), colIndex = k});
+                    }
+                    ICellStyle cellStyle = cell.CellStyle;
+                    //if(cellStyle.FillForegroundColorColor)
+                    byte[] rgb;
+                    if (request.filename.ToLower().IndexOf(".xlsx") > 0)
+                    {
+                        rgb = ((XSSFColor)cell.CellStyle.FillForegroundColorColor).RGB;
+                    }
+                    else 
+                    {
+                        rgb = ((HSSFColor)cell.CellStyle.FillForegroundColorColor).RGB;
+                    }
+                    if(rgb.Count() == 3 && rgb[0].ToString() == "255" && rgb[1].ToString() == "204" && rgb[2].ToString() == "153")
+                    //if (cell.ToString().IndexOf("价格表") > -1)
+                    {
+                        cmd.CommandText = "Select isnull(pricelistid,0) From u_pricelist where pricelistname = @pricelistname";
+                        cmd.Parameters.Clear();
+                        cmd.Parameters.AddWithValue("@pricelistname", cell.ToString());
+                        var pricelistid = Convert.ToInt32(cmd.ExecuteScalar());
+                        if (pricelistid > 0)
+                        {
+                            priceHeaders.Add(new HeaderPropetry { name = cell.ToString(), colIndex = k, keyId = pricelistid });
+                        }
+                        
+                    }
+                    //k++;
+                }
+                if (headers.Count <= 0 || priceHeaders.Count <= 0)
+                {
+                    rslt.ErrMsg = "excel格式不正确";
+                    return;
+                }
+                using (cmd.Transaction = con.BeginTransaction())
+                {
+                    try
+                    {
+
+
+                        for (int rowIndex = 1; rowIndex <= sheet.LastRowNum; rowIndex++)
+                         {
+                            row = sheet.GetRow(rowIndex);
+                            if (row == null) continue;
+
+                            var mtrltype = string.Empty;
+                            var mtrlname = string.Empty;
+                            foreach (var head in headers)
+                            {
+                                ICell cell = row.GetCell(head.colIndex);
+                                if (cell == null || cell.ToString() == "") continue;
+                                if (head.name == "类别")
+                                {
+                                    mtrltype = GetCellValue(cell).ToString();
+                                }
+                                else if (head.name == "名称")
+                                {
+                                    mtrlname = GetCellValue(cell).ToString();
+                                }
+                            }
+                            if (!string.IsNullOrEmpty(mtrltype) && !string.IsNullOrEmpty(mtrlname))
+                            {
+
+                                foreach (var pricename in priceHeaders)
+                                {
+                                    var mtrlid = 0;
+                                    cmd.CommandText = @"Select isnull(u_mtrl_price.mtrlid,0) from u_mtrl_price 
+                            where u_mtrl_price.mtrltype = (select isnull(mtrltypeid,0) from u_mtrltype where mtrltype = @mtrltype)
+                            and u_mtrl_price.name = @mtrlname";
+                                    cmd.Parameters.Clear();
+                                    cmd.Parameters.AddWithValue("@mtrltype", mtrltype);
+                                    cmd.Parameters.AddWithValue("@mtrlname", mtrlname);
+                                    mtrlid = Convert.ToInt32(cmd.ExecuteScalar());
+                                    if (mtrlid == 0)
+                                    {
+                                        //throw new Exception(string.Format("类别:{0},名称:{1}的物料类别或物料不存在",mtrltype,mtrlname));
+                                        break;
+                                    }
+                                    var updatePrice = new u_mtrl_price_pricelist { mtrlid = mtrlid, pricelistid = pricename.keyId };
+                                    ICell cell = row.GetCell(pricename.colIndex);
+                                    updatePrice.price = Convert.ToDecimal(GetCellValue(cell));
+                                    DbSqlHelper.InsertOrUpdate(cmd, updatePrice, "price");
+                                }
+                            }
+                        }
+                        cmd.Transaction.Commit();
+                    }
+                    catch (Exception ex)
+                    {
+                        cmd.Transaction.Rollback();
+                        rslt.ErrMsg = ex.Message;
+                    }
+                }
+               
+            }
+        }
+        private object GetCellValue(ICell cell)
+        {
+            if (cell == null) return null;
+            switch (cell.CellType)
+            {
+                case CellType.Numeric:
+                    if (DateUtil.IsCellDateFormatted(cell))
+                    {
+                        return cell.DateCellValue.ToString("yyyy-MM-dd");
+                    }
+                    else
+                    {
+                        return cell.NumericCellValue;
+                    }
+                case CellType.Boolean:
+                    return cell.BooleanCellValue;
+                default:
+                    return cell.ToString().Trim();
+            }
+        }
+        public class HeaderPropetry
+        {
+            public string name { get; set; }
+            public int colIndex { get; set; }
+            public int keyId { get; set; }
+        }
+    }
+}

+ 1 - 0
JLHHJSvr/GlobalVar/GlobalVar.cs

@@ -238,6 +238,7 @@ namespace JLHHJSvr
 
                 excutorManager.AddMap("JLH_FetchPrice", typeof(JLH_FetchPriceRequest), new JLH_FetchPriceExcutor());
                 excutorManager.AddMap("GetResetWiptype", typeof(GetResetWiptypeRequest), new GetResetWiptypeExcutor());
+                excutorManager.AddMap("ImportMtrlPriceByExcel", typeof(ImportMtrlPriceByExcelRequest), new ImportMtrlPriceByExcelExcutor());
             }
             catch (Exception ex)
             {

+ 10 - 8
JLHHJSvr/JLHHJSvr.csproj

@@ -44,17 +44,17 @@
     <Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
       <HintPath>..\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
     </Reference>
-    <Reference Include="NPOI, Version=2.1.1.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
-      <HintPath>..\packages\NPOI.Excel.2.1.1\lib\NPOI.dll</HintPath>
+    <Reference Include="NPOI, Version=2.2.1.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
+      <HintPath>..\packages\NPOI.2.2.1\lib\net40\NPOI.dll</HintPath>
     </Reference>
-    <Reference Include="NPOI.OOXML, Version=2.1.1.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
-      <HintPath>..\packages\NPOI.Excel.2.1.1\lib\NPOI.OOXML.dll</HintPath>
+    <Reference Include="NPOI.OOXML, Version=2.2.1.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
+      <HintPath>..\packages\NPOI.2.2.1\lib\net40\NPOI.OOXML.dll</HintPath>
     </Reference>
-    <Reference Include="NPOI.OpenXml4Net, Version=2.1.1.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
-      <HintPath>..\packages\NPOI.Excel.2.1.1\lib\NPOI.OpenXml4Net.dll</HintPath>
+    <Reference Include="NPOI.OpenXml4Net, Version=2.2.1.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
+      <HintPath>..\packages\NPOI.2.2.1\lib\net40\NPOI.OpenXml4Net.dll</HintPath>
     </Reference>
-    <Reference Include="NPOI.OpenXmlFormats, Version=2.1.1.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
-      <HintPath>..\packages\NPOI.Excel.2.1.1\lib\NPOI.OpenXmlFormats.dll</HintPath>
+    <Reference Include="NPOI.OpenXmlFormats, Version=2.2.1.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
+      <HintPath>..\packages\NPOI.2.2.1\lib\net40\NPOI.OpenXmlFormats.dll</HintPath>
     </Reference>
     <Reference Include="System" />
     <Reference Include="System.configuration" />
@@ -104,6 +104,7 @@
     <Compile Include="Com\DeleteMattressExtra.cs" />
     <Compile Include="Com\GetResetWiptype.cs" />
     <Compile Include="Com\GetMattressSubspecs.cs" />
+    <Compile Include="Com\ImportMtrlPriceByExcel.cs" />
     <Compile Include="Com\JLH_FetchPrice.cs" />
     <Compile Include="Com\ChangePassword.cs" />
     <Compile Include="Com\Model\u_sc_workgroup_erp.cs" />
@@ -307,6 +308,7 @@
     <Compile Include="Excutor\GetFormulaVarListExcutor.cs" />
     <Compile Include="Excutor\GetResetWiptypeExcutor.cs" />
     <Compile Include="Excutor\GetMattressSubspecsExcutor.cs" />
+    <Compile Include="Excutor\ImportMtrlPriceByExcelExcutor.cs" />
     <Compile Include="Excutor\JLH_FetchPriceExcutor.cs" />
     <Compile Include="Excutor\ChangePasswordExcutor.cs" />
     <Compile Include="Excutor\SaveMattressExtraTypeExcutor.cs" />

+ 2 - 0
JLHHJSvr/packages.config

@@ -1,4 +1,6 @@
 <?xml version="1.0" encoding="utf-8"?>
 <packages>
   <package id="Newtonsoft.Json" version="13.0.3" targetFramework="net45" />
+  <package id="NPOI" version="2.2.1" targetFramework="net45" />
+  <package id="SharpZipLib" version="0.86.0" targetFramework="net45" />
 </packages>

+ 6 - 0
JLHWEB/src/api/modules/basicinfo.ts

@@ -526,3 +526,9 @@ export const GetFormulaVarList = () => {
 export const FormulaCheck = (params: Basicinfo.ReqFormulaCheck) => {
   return http.post(PORT1 + `/FormulaCheck`, params);
 };
+/**
+ * @name 导入数据(物料价格表)
+ */
+export const ImportMtrlPrice = (params: any) => {
+  return http.post(PORT1 + `/ImportMtrlPriceByExcel`, params);
+};

+ 144 - 0
JLHWEB/src/views/baseinfo/mtrldef/components/ImportPrice.vue

@@ -0,0 +1,144 @@
+<template>
+  <LJDialog ref="DialogRef">
+    <el-upload
+      ref="uploadRef"
+      class="upload-demo"
+      v-model:file-list="fileList"
+      drag
+      action="#"
+      :auto-upload="false"
+      v-bind="$attrs"
+      :on-change="handelChange"
+      :on-exceed="handleExceed"
+      :limit="1"
+      :format="['xls', 'xlsx']"
+      accept=".xls, .xlsx"
+    >
+      <template #trigger>
+        <el-button type="primary">选择文件</el-button>
+      </template>
+    </el-upload>
+    <div style="text-align: right">
+      <el-button class="ml-3" type="success" @click="confirm"> 导入 </el-button>
+    </div>
+  </LJDialog>
+</template>
+
+<script setup lang="tsx" name="ImportPrice">
+import { ref, nextTick } from "vue";
+import { ElMessage } from "element-plus";
+import { ImportMtrlPrice } from "@/api/modules/basicinfo";
+import LJDialog from "@/components/LjDialog/index.vue";
+import { base64 } from "js-md5";
+//import type { FileParams } from "../index.vue";
+
+interface UploadWidgetProps {
+  limit?: number;
+  //params: FileParams;
+}
+
+const props = withDefaults(defineProps<UploadWidgetProps>(), {
+  limit: 1
+});
+
+const emit = defineEmits(["uploaded"]);
+const basedata = ref();
+const fileList = ref([]);
+// const popoverRef = ref();
+const visible = ref(false);
+const uploading = ref(false);
+const successStatus = ref(false);
+const closeTimer = ref();
+const toCloseTime = ref(3);
+const DialogRef = ref();
+const uploadRef = ref();
+/**
+ * @description 上传文件
+ * @param data
+ */
+const afterReader = async (data: any) => {
+  console.log("afterReader :>> ", data);
+
+  await ImportMtrlPrice({
+    filename: data[0].fileName,
+    base64: data[0].base64
+  });
+
+  // setTimeout(() => {
+  ElMessage.success("导入成功");
+  successStatus.value = true;
+  setTimeout(() => {
+    DialogRef.value.hide();
+  }, 500);
+  //   closeTimer.value = setInterval(() => {
+  //     toCloseTime.value--;
+  //     if (toCloseTime.value <= 0) {
+  //       handleClose();
+  //     }
+  //   }, 1000);
+  // }, 2000);
+};
+
+const confirm = async () => {
+  toCloseTime.value = 3;
+  //   console.log("fileList :>> ", fileList.value);
+  if (!fileList.value.length) {
+    ElMessage.warning("请选择文件");
+    return;
+  }
+  uploading.value = true;
+  // 读取文件内容
+  let base64List: any = [];
+  let successKey = 0;
+  fileList.value.map((item: any, index: number) => {
+    console.log("fileList item :>> ", item, item.raw);
+    // 创建FileReader对象
+    const reader = new FileReader();
+    // 读取文件内容
+    reader.readAsDataURL(item.raw);
+    //reader.readAsArrayBuffer(item.raw);
+    // 当文件读取完成时的回调函数, 将文件内容转换为base64格式
+    reader.onload = () => {
+      let netIndex = item.name.lastIndexOf("."); // 获取最后一个.的位置
+      let file = {
+        //...props.params,
+        //fileName: item.name.substring(0, netIndex),
+        //fileType: item.name.substring(netIndex + 1),
+        fileName: item.name,
+        base64: reader.result
+        //ClassID: props.params.classid
+      };
+      base64List.push(file);
+      successKey++;
+      // 将文件内容转换为base64格式
+      console.log("reader.result :>> ", index, successKey, reader.result);
+      if (successKey == fileList.value.length) {
+        afterReader(base64List);
+      }
+    };
+  });
+};
+const handelChange = (file: any) => {};
+const handleExceed = (files: any) => {
+  uploadRef.value.clearFiles();
+  nextTick(() => {
+    uploadRef.value.handleStart(files[0]);
+  });
+};
+const handleClose = () => {
+  clearInterval(closeTimer.value);
+  uploading.value = false;
+  fileList.value = [];
+  emit("uploaded");
+  //visible.value = false;
+  successStatus.value = false;
+  DialogRef.value.hide();
+};
+const show = () => {
+  DialogRef.value.show();
+  fileList.value = [];
+};
+defineExpose({
+  show
+});
+</script>

+ 7 - 2
JLHWEB/src/views/baseinfo/mtrldef/index.vue

@@ -37,7 +37,7 @@
               <el-button @click="handleCopyMtrldef">物料复制</el-button>
               <el-button @click="handleShowCopyForm">批修改</el-button>
               <el-button @click="handleModifyPrice">批修改单价</el-button>
-              <el-button>读取单价</el-button>
+              <el-button @click="handleImportData">读取单价</el-button>
             </el-button-group>
           </template>
         </LjVxeTable>
@@ -116,6 +116,7 @@
       </div>
     </template>
   </el-dialog>
+  <ImportPrice ref="ImportPriceRef" />
 </template>
 
 <script setup lang="ts" name="baseinfo_mtrldeflist">
@@ -133,6 +134,7 @@ import { cloneDeep } from "lodash-es";
 import { traverseNode } from "@/utils/index";
 import { ElMessage, ElMessageBox } from "element-plus";
 import { getCurrentRecords } from "@/utils/index";
+import ImportPrice from "./components/ImportPrice.vue";
 
 const dwname = "web_mtrldeflist";
 const mainData = ref({});
@@ -146,6 +148,7 @@ const tableProps = {
   //   filename: t("menu.saletaskmx") + formatToDate(new Date(), "YYYY-MM-DD HH:mm:ss")
   // }
 };
+const ImportPriceRef = ref();
 
 const layoutSetting = {
   dwname: dwname,
@@ -407,7 +410,9 @@ const handleModifyPrice = () => {
   priceListFormParams.value.pricelistid_to = curRecords[0].pricelistid;
   priceListFormParams.value.rate = 1;
 };
-
+const handleImportData = () => {
+  ImportPriceRef.value.show();
+};
 // 返回绑定的事件
 const tableEvents = {
   "cell-dblclick": handleDBlClickTable