Procházet zdrojové kódy

1. 模板中,增加“从Excel中追加数据”的功能

djs před 2 měsíci
rodič
revize
2bf2493e79

+ 7 - 0
MeterVision/MeterVision.csproj

@@ -245,6 +245,9 @@
     <Compile Include="Patch\UCCompMain.xaml.cs">
       <DependentUpon>UCCompMain.xaml</DependentUpon>
     </Compile>
+    <Compile Include="Stand\AppendFromExcel.xaml.cs">
+      <DependentUpon>AppendFromExcel.xaml</DependentUpon>
+    </Compile>
     <Compile Include="Stand\SelecteStationDlg.xaml.cs">
       <DependentUpon>SelecteStationDlg.xaml</DependentUpon>
     </Compile>
@@ -428,6 +431,10 @@
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>
     </Page>
+    <Page Include="Stand\AppendFromExcel.xaml">
+      <SubType>Designer</SubType>
+      <Generator>MSBuild:Compile</Generator>
+    </Page>
     <Page Include="Stand\SelecteStationDlg.xaml">
       <SubType>Designer</SubType>
       <Generator>MSBuild:Compile</Generator>

+ 2 - 2
MeterVision/Properties/AssemblyInfo.cs

@@ -51,5 +51,5 @@ using System.Windows;
 // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
 // 方法是按如下所示使用“*”: :
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("3.3.1.6")]
-[assembly: AssemblyFileVersion("3.3.1.6")]
+[assembly: AssemblyVersion("3.3.1.8")]
+[assembly: AssemblyFileVersion("3.3.1.8")]

+ 4 - 2
MeterVision/Stand/AddStandDialog.xaml.cs

@@ -223,10 +223,12 @@ namespace MeterVision.Stand
                     importDlg.PrgIndex = row;
                     //判断图像是否符合要求的规格
                     string srcImage = worksheet.Cells[row, 1].Text.Trim();
-                    if (!ThisApp.IsImageDimensionsValid(srcImage))
+
+                    //为了导入excel表格中的内容,先暂时不判断文件是否满足要求
+                    /*if (!ThisApp.IsImageDimensionsValid(srcImage))
                     {
                         continue;
-                    }
+                    }*/
 
                     var standDetail = new TStandDetail
                     {

+ 46 - 0
MeterVision/Stand/AppendFromExcel.xaml

@@ -0,0 +1,46 @@
+<Window x:Class="MeterVision.Stand.AppendFromExcel"
+        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
+        xmlns:local="clr-namespace:MeterVision.Stand"
+        mc:Ignorable="d"
+        ShowInTaskbar="False"
+        ResizeMode="NoResize"
+        Background="WhiteSmoke"
+        WindowStartupLocation="CenterOwner"
+        Title="从Excel追加数据" Height="180" Width="320">
+    <Grid>
+        <Grid.RowDefinitions>
+            <RowDefinition Height="*" />
+            <RowDefinition Height="40" />
+        </Grid.RowDefinitions>
+
+        <Border Grid.Row="0" BorderBrush="#D3D3D3" BorderThickness="1" Margin="10 10 10 0" Background="White">
+            <!-- Excel文件选择区域,初始时隐藏 -->
+            <StackPanel Grid.Row="0" Orientation="Vertical" Margin="20,20,20,0" Visibility="Visible" x:Name="ExcelImportPanel">
+                <TextBlock Text="请选择Excel:" HorizontalAlignment="Left" VerticalAlignment="Center" 
+                               FontSize="14px" Foreground="#333333" Margin="0 0 0 5"  />
+                <Grid>
+                    <Grid.ColumnDefinitions>
+                        <ColumnDefinition Width="*"/>
+                        <ColumnDefinition Width="Auto"/>
+                    </Grid.ColumnDefinitions>
+                    <TextBox Name="txtExcelFile" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Center"
+                                 IsReadOnly="True"
+                                 Foreground="#000000" Padding="2" FontSize="14px" Margin="0,0,2,0"/>
+                    <Button Name="btnImportExcel" Grid.Column="1" Content="..." Width="28" Height="26" VerticalAlignment="Center" Click="BtnImportExcel_Click" />
+                </Grid>
+            </StackPanel>
+        </Border>
+
+        <!-- 按钮区域 -->
+        <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center">
+            <Button Name="btnOK" Content="确定" HorizontalAlignment="Center" Margin="0 0 20 0"
+                    VerticalAlignment="Center" Width="80" Height="26" Click="BtnOK_Click" />
+            <Button Name="btnClose" Content="取消" HorizontalAlignment="Center" 
+                    VerticalAlignment="Center" Width="80" Height="26" Click="BtnClose_Click" />
+        </StackPanel>
+
+    </Grid>
+</Window>

+ 170 - 0
MeterVision/Stand/AppendFromExcel.xaml.cs

@@ -0,0 +1,170 @@
+using MeterVision.db;
+using MeterVision.Dlg;
+using OfficeOpenXml;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using Microsoft.Win32;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+
+namespace MeterVision.Stand
+{
+    /// <summary>
+    /// AppendFromExcel.xaml 的交互逻辑
+    /// </summary>
+    public partial class AppendFromExcel : Window
+    {
+        //新增的TStand
+        //public TStand mTStand { get; set; }
+        public List<TStandDetail> mStandDetailList;
+
+        public AppendFromExcel()
+        {
+            InitializeComponent();
+
+        }
+
+        private void BtnImportExcel_Click(object sender, RoutedEventArgs e)
+        {
+            // 打开文件选择对话框
+            var openFileDialog = new OpenFileDialog
+            {
+                //Filter = "Excel Files (*.xls;*.xlsx)|*.xls;*.xlsx",
+                Filter = "Excel Files (*.xlsx)|*.xlsx",
+                Title = "选择Excel文件"
+            };
+
+            if (openFileDialog.ShowDialog() == true)
+            {
+                // 显示选择的文件名
+                txtExcelFile.Text = openFileDialog.FileName;
+                /*if (string.IsNullOrWhiteSpace(txtStandName.Text.Trim()))
+                {
+                    txtStandName.Text = ThisApp.GetFileNameWithoutExtension(txtExcelFile.Text.Trim());
+                }*/
+            }
+        }
+
+        private async void BtnOK_Click(object sender, RoutedEventArgs e)
+        {
+            string filePath = txtExcelFile.Text.Trim();
+            if (string.IsNullOrWhiteSpace(filePath))
+            {
+                MessageBox.Show(Application.Current.MainWindow, "请选择Excel文件!", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
+                return;
+            }
+
+            bool blLoad = await LoadTStandDetailList(filePath);
+
+            this.DialogResult = true;
+            this.Close();
+        }
+
+        //加载列表数据
+        private async Task<bool> LoadTStandDetailList(string fileName)
+        {
+            string titleInfo = "正在获取数据,请稍候...";
+            WaitImportDlg waitWindow = new WaitImportDlg(titleInfo)
+            {
+                Owner = this,
+                WindowStartupLocation = WindowStartupLocation.CenterOwner
+            };
+
+            waitWindow.Show();
+
+            try
+            {
+                await Task.Run(() =>
+                {
+                    //ImportExcel(mTStand.StandFile, waitWindow);
+                    ImportExcel(fileName, waitWindow);
+                });
+                // 如果mStandDetailList不为空,则表示导入成功
+                return mStandDetailList != null && mStandDetailList.Count > 0;
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show(this, $"获取Excel数据失败:{ex.Message}", "错误",
+                    MessageBoxButton.OK, MessageBoxImage.Error);
+                return false;
+            }
+            finally
+            {
+                waitWindow.Close();
+            }
+        }
+
+        public void ImportExcel(string filePath, WaitImportDlg importDlg)
+        {
+            mStandDetailList = new List<TStandDetail>();
+
+            Console.WriteLine($"正在读取文件: {filePath}");
+            using (var package = new ExcelPackage(new FileInfo(filePath)))
+            {
+                Console.WriteLine($"工作表数量: {package.Workbook.Worksheets.Count}");
+                //检查是否存在工作表
+                if (package.Workbook.Worksheets.Count == 0)
+                {
+                    throw new InvalidOperationException("Excel文件中没有工作表。");
+                }
+
+                // 获取第一个工作表
+                var worksheet = package.Workbook.Worksheets[1];
+
+                // 获取总行数
+                int rowCount = worksheet.Dimension?.Rows ?? 0;
+                Console.WriteLine($"行数: {rowCount}");
+
+                importDlg.PrgCount = rowCount;
+
+                // 遍历每一行
+                for (int row = 2; row <= rowCount; row++) // 假设第一行是标题行
+                {
+                    importDlg.PrgIndex = row;
+                    //判断图像是否符合要求的规格
+                    string srcImage = worksheet.Cells[row, 1].Text.Trim();
+
+                    //为了导入excel表格中的内容,先暂时不判断文件是否满足要求
+                    /*if (!ThisApp.IsImageDimensionsValid(srcImage))
+                    {
+                        continue;
+                    }*/
+
+                    var standDetail = new TStandDetail
+                    {
+                        StandDetailId = Guid.NewGuid().ToString(),
+                        CreateTime = ThisApp.GetNowTime_yyyyMMddHHmmss(),
+                        //StandId = mTStand.StandId,
+                        // 读取图像路径(假设图像路径在A列)
+                        SrcImage = worksheet.Cells[row, 1].Text.Trim(),
+                        // 读取标准答案(假设标准答案在B列)
+                        StandValue = worksheet.Cells[row, 2].Text.Trim(),
+                        DeviceSn = worksheet.Cells[row, 3].Text.Trim(),
+                        StationId = worksheet.Cells[row, 4].Text.Trim(),
+                        SampleTime = worksheet.Cells[row, 5].Text.Trim(),
+                        ENumCount = ThisApp.ConvertToInt(worksheet.Cells[row, 6].Text.Trim()),
+                        ELastUnit = ThisApp.ConvertToInt(worksheet.Cells[row, 7].Text.Trim())
+                    };
+                    // 添加到结果列表
+                    mStandDetailList.Add(standDetail);
+                }
+            }
+        }
+
+        private void BtnClose_Click(object sender, RoutedEventArgs e)
+        {
+            this.Close();
+        }
+        //---------------------------------------------------------------------------
+    }
+}

+ 6 - 0
MeterVision/Stand/UCStandMain.xaml

@@ -185,6 +185,12 @@
                                         <Image Source="pack://application:,,,/MeterVision;component/Assest/import.png" Width="16" Height="16"/>
                                     </MenuItem.Icon>
                                 </MenuItem>
+                                <Separator />
+                                <MenuItem x:Name="miAppendExcel" Header="追加站点数据(来自Excel)" Click="MiAppendExcel_Click">
+                                    <MenuItem.Icon>
+                                        <Image Source="pack://application:,,,/MeterVision;component/Assest/import.png" Width="16" Height="16"/>
+                                    </MenuItem.Icon>
+                                </MenuItem>
                             </ContextMenu>
                         </DataGrid.ContextMenu>
 

+ 79 - 0
MeterVision/Stand/UCStandMain.xaml.cs

@@ -1262,6 +1262,85 @@ namespace MeterVision.Stand
 
             return null;
         }
+
+        private void MiAppendExcel_Click(object sender, RoutedEventArgs e)
+        {
+            AppendExcel();
+        }
+
+        private async void AppendExcel()
+        {
+            var dialog = new AppendFromExcel()
+            {
+                Owner = Application.Current.MainWindow,
+                WindowStartupLocation = WindowStartupLocation.CenterOwner
+            };
+            if (dialog.ShowDialog() == true)
+            {
+                List<TStandDetail> standDetailList = dialog.mStandDetailList;
+                if(standDetailList == null || standDetailList.Count == 0)
+                {
+                    MessageBox.Show(Application.Current.MainWindow, "Excel中没有查询到数据", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
+                    return;
+                }
+
+                List<TStation> stationList = DBStation.GetAllVStation2(SelectedStandItem.StandId);
+
+                List<TStandDetail> allStandDetails = new List<TStandDetail>();
+                foreach(var station in stationList)
+                {
+                    for(int i = 0; i < standDetailList.Count; i++)
+                    {
+                        if(standDetailList[i].StationId == station.StationId)
+                        {
+                            standDetailList[i].StandId = SelectedStandItem.StandId;
+                            allStandDetails.Add(standDetailList[i]);
+                        }
+                    }//for i
+                }//foreach
+
+                bool blInsert = await InsertDatatBase(allStandDetails);
+                MessageBox.Show(Application.Current.MainWindow, $"追加Excel数据{(blInsert ? "成功" : "失败")}", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
+
+                //刷新模板
+                VStand vStand = DBStand.GetVStandById(SelectedStandItem.StandId);
+                StandItem standItem = new StandItem(vStand);
+                ObjectHelper.CopyMatchingFields(standItem, SelectedStandItem);
+                OnPropertyChanged(nameof(SelectedStandItem));
+            }
+        }
+
+        private async Task<bool> InsertDatatBase(List<TStandDetail> standDetails)
+        {
+            bool blInsert = false;
+
+            string titleInfo = "正在插入数据库,请稍候...";
+            WaitWindow waitWindow = new WaitWindow(titleInfo)
+            {
+                Owner = Application.Current.MainWindow,
+                WindowStartupLocation = WindowStartupLocation.CenterOwner
+            };
+
+            waitWindow.Show();
+
+            try
+            {
+                await Task.Run(() =>
+                {
+                    blInsert = DBStand.InsertStandDetails(standDetails);                   
+                });
+            }
+            catch (Exception ex)
+            {
+                MessageBox.Show($"插入数据失败:{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
+            }
+            finally
+            {
+                waitWindow.Close();
+            }
+            return blInsert;
+        }
+
         /////////////////////////////////////////////////////////////////////////////
     }
 

+ 43 - 0
MeterVision/db/DBStation.cs

@@ -567,6 +567,49 @@ namespace MeterVision.db
             return stations;
         }
 
+        public static List<TStation> GetAllVStation2(string standId)
+        {
+            // 查询分页数据
+            string sql = $@"
+                SELECT id, stand_id, station_id, create_time, mark_count
+                FROM v_station
+                WHERE stand_id = @StandId
+                ORDER BY station_id ASC";
+
+            // 定义参数
+            SQLiteParameter[] parameters = new SQLiteParameter[]
+            {
+                new SQLiteParameter("@StandId", standId)
+            };
+
+            // 执行查询并读取数据
+            List<TStation> stations = new List<TStation>();
+            try
+            {
+                using (SQLiteDataReader reader = SQLiteHelper.ExecuteReader(sql, parameters.ToArray()))
+                {
+                    while (reader.Read())
+                    {
+                        TStation station = new TStation
+                        {
+                            Id = reader.GetString(reader.GetOrdinal("id")),
+                            StandId = reader.GetString(reader.GetOrdinal("stand_id")),
+                            StationId = reader.GetString(reader.GetOrdinal("station_id")),
+                            CreateTime = reader.GetString(reader.GetOrdinal("create_time")),
+                            MarkCount = reader.GetInt32(reader.GetOrdinal("mark_count"))
+                        };
+                        stations.Add(station);
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                // 根据需要记录日志或抛出异常
+                throw new Exception($"查询 TStation表 时发生错误:{ex.Message}", ex);
+            }
+
+            return stations;
+        }
 
         public static bool DeleteTStation(string id)
         {