WPF注册登录页面,同时将注册信息保存到一个excel中

参考:

https://www.cnblogs.com/wolfocme110/p/3881039.html

https://blog.csdn.net/qq_41953178/article/details/94615692

<Window x:Class="WpfApp3.MainWindow"
        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:WpfApp3"
        mc:Ignorable="d"
        Title="Login" Height="450" Width="800">
    <Grid>
        <Label Content="User" HorizontalAlignment="Left" Margin="196,105,0,0" VerticalAlignment="Top" Width="100" FontSize="22"/>
        <Label Content="Password" HorizontalAlignment="Left" Margin="196,154,0,0" VerticalAlignment="Top" Width="100" FontSize="22"/>
        <Button Content="Login" HorizontalAlignment="Left" Margin="461,263,0,0" VerticalAlignment="Top" Width="91" Click="Login_Click"/>
        <TextBox x:Name="user" HorizontalAlignment="Left" Height="27" Margin="342,117,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="189" RenderTransformOrigin="1.008,0.41"/>
        <TextBox x:Name="password" HorizontalAlignment="Left" Height="27" Margin="342,166,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="189" RenderTransformOrigin="1.008,0.41"/>
        <Button Content="Regist" HorizontalAlignment="Left" Margin="324,263,0,0" VerticalAlignment="Top" Width="91" Click="Button_Click" RenderTransformOrigin="0.516,3.5"/>

    </Grid>
</Window>
using System;
using System.Collections;
using System.Windows;


namespace WpfApp3
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }
     

        private void Login_Click(object sender, RoutedEventArgs e)
        {
            //数据格式校验,正则表达式
            string u = user.Text;
            string p = password.Text;
            bool isLogin = false;

            if (String.IsNullOrEmpty(u))
            {
                MessageBox.Show("user is not null");
                return;
            }
            if (String.IsNullOrEmpty(p))
            {
                MessageBox.Show("password is not null");
                return;
            }
            Hashtable users =(Hashtable) Application.Current.Properties["users"];
            
            if (users != null)
            {
                //MessageBox.Show("not null");
                foreach (DictionaryEntry user in users)
                {
                    if (user.Key.Equals(u) && user.Value.Equals(p))
                    {
                        isLogin = true;
                    }
                }
            }
            if (isLogin)
            {
                MessageBox.Show("login success!");
            }
            else
            {
                MessageBox.Show("username or password is wrong");
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Regist r = new Regist();
            r.WindowStartupLocation = WindowStartupLocation.Manual;   //使新窗口位置在原来的位置上
            r.Left = this.Left;  //使新窗口位置在原来的位置上
            r.Top = this.Top;  //使新窗口位置在原来的位置上
            r.Show();  //打开新窗口
            this.Close();
        }
    }
}
<Window x:Class="WpfApp3.Regist"
        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:WpfApp3"
        mc:Ignorable="d"
        Title="Regist" Height="450" Width="800">
    <Grid>
        <Label Content="User" HorizontalAlignment="Left" Margin="43,71,0,0" VerticalAlignment="Top" Width="132" FontSize="22"/>
        <Label Content="Password" HorizontalAlignment="Left" Margin="43,120,0,0" VerticalAlignment="Top" Width="132" FontSize="22"/>
        <Button Content="Regist" HorizontalAlignment="Left" Margin="286,260,0,0" VerticalAlignment="Top" Width="107" Click="Regist_Click"/>
        <TextBox x:Name="user" HorizontalAlignment="Left" Height="27" Margin="204,83,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="189" RenderTransformOrigin="1.008,0.41"/>
        <TextBox x:Name="password" HorizontalAlignment="Left" Height="27" Margin="204,132,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="189" RenderTransformOrigin="1.008,0.41"/>
        <TextBox x:Name="repassword" HorizontalAlignment="Left" Height="27" Margin="204,181,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="189" RenderTransformOrigin="1.008,0.41"/>
        <Label HorizontalAlignment="Left" Margin="43,181,0,0" VerticalAlignment="Top" Width="132" FontSize="22"/>
        <Label Content="Repassword" HorizontalAlignment="Left" Margin="43,179,0,0" VerticalAlignment="Top" Width="132" FontSize="22" RenderTransformOrigin="0.523,0.279"/>

    </Grid>
</Window>
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections;
using System.Collections.Generic;
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 System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Excel = Microsoft.Office.Interop.Excel;
using Window = System.Windows.Window;
using System.Diagnostics;

namespace WpfApp3
{
    /// <summary>
    /// Interaction logic for Regist.xaml
    /// </summary>
    public partial class Regist : Window
    {
        public static Hashtable userall;
        public Regist()
        {
            InitializeComponent();
        }
        
        private void Regist_Click(object sender, RoutedEventArgs e)
        {
            string u = user.Text;
            string p = password.Text;
            string rp = repassword.Text;
            Program program = new Program();

            if (String.IsNullOrEmpty(u))
            {
                MessageBox.Show("user is not null");
                return;
            }
            if (String.IsNullOrEmpty(p))
            {
                MessageBox.Show("password is not null");
                return;
            }
            if (String.IsNullOrEmpty(rp))
            {
                MessageBox.Show("Repassword is not null");
                return;
            }
            if (!p.Equals(rp))
            {
                MessageBox.Show("password is not equals repassword");
                return;
            }

            userall = program.readExcel();
            if (userall == null)
            {
                userall = new Hashtable();
                userall.Add(u, p);
            }
            else
            {
                bool isexist = userall.ContainsKey(u);
                if (isexist)
                {
                    MessageBox.Show("user is exist!");
                    return;
                }
                else
                {
                    userall.Add(u, p);
                    Console.WriteLine(userall.Count);
                }
            }


            //Hashtable hh = program.readExcel();
            //userall.Add(hh);
            //MessageBox.Show(userall.Count.ToString());
            System.Windows.Application.Current.Properties["users"] = userall;

            program.InsertExcel(u, p);

            /*System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("username");
            dt.Columns.Add("password");
            System.Data.DataRow dr = dt.NewRow();
            dr[0] = u;
            dr[1] = p;
            dt.Rows.Add(dr);
            Program program = new Program();
            program.ExcelExport(dt, "USERS");*/

            

            MessageBox.Show("regist success!");
            MainWindow l = new MainWindow();
            l.WindowStartupLocation = WindowStartupLocation.Manual;   //使新窗口位置在原来的位置上
            l.Left = this.Left;  //使新窗口位置在原来的位置上
            l.Top = this.Top;  //使新窗口位置在原来的位置上
            l.Show();  //打开新窗口
            this.Close();
        }
    }


    //
    class Program
    {
        public void InsertExcel(string u, string p)
        {
            //1.创建Excel
            Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); ;
            try
            {
                

                //2.打开已经存在的工作簿
                string path = "C:\\Users\\zewei.cao\\Desktop\\Copy of users.xlsx";
                ExcelApp.Workbooks.Open(path);
                //3.
                ExcelApp.Cells[1, 1].Value = "username";
                ExcelApp.Cells[1, 2].Value = "password";

                ExcelApp.ActiveSheet.Rows[2].Insert(u, p);

                ExcelApp.Cells[2, 1].Value = u;
                ExcelApp.Cells[2, 2].Value = p;


                ExcelApp.DisplayAlerts = false; //保存Excel的时候,不弹出是否保存的窗口直接进行保存 
                //4.保存工作表
                ExcelApp.ActiveWorkbook.Save();

            }
            catch
            {
                System.Windows.MessageBox.Show("导出文件保存失败,可能原因该文件已打开!", "警告!");
            }
            finally
            {
                //5.关闭工作簿
                ExcelApp.ActiveWorkbook.Close();
                //6.退出excel
                ExcelApp.Quit();
            }

        }


        public Hashtable readExcel()
        {
            Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); ;
            try
            {
                //2.打开已经存在的工作簿
                string path = "C:\\Users\\zewei.cao\\Desktop\\Copy of users.xlsx";
                //ExcelApp.Workbooks.Open(path, ReadOnly: true);
                Hashtable h = new Hashtable();

                Excel.Workbook wb = ExcelApp.Application.Workbooks.Open(path, ReadOnly: true);
                Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.get_Item(1);
                int rowsint = ws.UsedRange.Cells.Rows.Count; //得到行数
                Excel.Range rng1 = ws.Cells.get_Range("A2", "A" +rowsint);
                Excel.Range rng2 = ws.Cells.get_Range("B2", "B" +rowsint);

                object[,] arry1 = (object[,])rng1.Value2;   //get range’s value
                object[,] arry2 = (object[,])rng2.Value2;

                string[,] arry = new string[rowsint - 1, 2];
                for(int i = 1; i <= rowsint-2; i++)
                {
                    arry[i - 1, 0] = arry1[i, 1].ToString();
                    arry[i - 1, 1] = arry2[i, 1].ToString();
                    h.Add(arry1[i, 1].ToString(), arry2[i, 1].ToString());
                    Console.WriteLine(arry1[i, 1].ToString() + " :"+arry2[i, 1].ToString());
                }
                
                return h;
            }
            catch
            {
                MessageBox.Show("read excel error");
                return null;
            }
            finally
            {
                //5.关闭工作簿
                ExcelApp.ActiveWorkbook.Close();
                //6.退出excel
                ExcelApp.Quit();
            }
        }
/*
        public string ExcelExport(System.Data.DataTable DT, string title)
        {
            try
            {
                //创建Excel
                Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel.Workbook ExcelBook = ExcelApp.Workbooks.Add(System.Type.Missing);
                //创建工作表(即Excel里的子表sheet) 1表示在子表sheet1里进行数据导出
                Microsoft.Office.Interop.Excel.Worksheet ExcelSheet = (Microsoft.Office.Interop.Excel.Worksheet)ExcelBook.Worksheets[1];
                //如果数据中存在数字类型 可以让它变文本格式显示
                ExcelSheet.Cells.NumberFormat = "@";
                //设置工作表名
                ExcelSheet.Name = title;
                //设置Sheet标题
                string start = "A1";
                string end = ChangeASC(DT.Columns.Count) + "1";
                Microsoft.Office.Interop.Excel.Range _Range = (Microsoft.Office.Interop.Excel.Range)ExcelSheet.get_Range(start, end);
                _Range.Merge(0);                     //单元格合并动作(要配合上面的get_Range()进行设计)
                _Range = (Microsoft.Office.Interop.Excel.Range)ExcelSheet.get_Range(start, end);
                _Range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                _Range.Font.Size = 22; //设置字体大小
                _Range.Font.Name = "宋体"; //设置字体的种类 
                ExcelSheet.Cells[1, 1] = title;    //Excel单元格赋值
                _Range.EntireColumn.AutoFit(); //自动调整列宽
                //写表头
                for (int m = 1; m <= DT.Columns.Count; m++)
                {
                    ExcelSheet.Cells[2, m] = DT.Columns[m - 1].ColumnName.ToString();
                    start = "A2";
                    end = ChangeASC(DT.Columns.Count) + "2";
                    _Range = (Microsoft.Office.Interop.Excel.Range)ExcelSheet.get_Range(start, end);
                    _Range.Font.Size = 14; //设置字体大小
                    _Range.Font.Name = "宋体"; //设置字体的种类  
                    _Range.EntireColumn.AutoFit(); //自动调整列宽 
                    _Range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                }
                //写数据
                for (int i = 0; i < DT.Rows.Count; i++)
                {
                    for (int j = 1; j <= DT.Columns.Count; j++)
                    {
                        //Excel单元格第一个从索引1开始
                        // if (j == 0) j = 1;
                        ExcelSheet.Cells[i + 3, j] = DT.Rows[i][j - 1].ToString();
                    }
                }
                //表格属性设置
                for (int n = 0; n < DT.Rows.Count + 1; n++)
                {
                    start = "A" + (n + 3).ToString();
                    end = ChangeASC(DT.Columns.Count) + (n + 3).ToString();
                    //获取Excel多个单元格区域
                    _Range = (Microsoft.Office.Interop.Excel.Range)ExcelSheet.get_Range(start, end);
                    _Range.Font.Size = 12; //设置字体大小
                    _Range.Font.Name = "宋体"; //设置字体的种类
                    _Range.EntireColumn.AutoFit(); //自动调整列宽
                    _Range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; //设置字体在单元格内的对其方式 _Range.EntireColumn.AutoFit(); //自动调整列宽 
                }
                ExcelApp.DisplayAlerts = false; //保存Excel的时候,不弹出是否保存的窗口直接进行保存 
                弹出保存对话框,并保存文件
                Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                sfd.DefaultExt = ".xlsx";
                sfd.Filter = "Office 2007 File|*.xlsx|Office 2000-2003 File|*.xls|所有文件|*.*";
                if (sfd.ShowDialog() == true)
                {
                    if (sfd.FileName != "")
                    {
                        ExcelBook.SaveAs(sfd.FileName);  //将其进行保存到指定的路径
                        System.Windows.MessageBox.Show("导出文件已存储为: " + sfd.FileName, "温馨提示");
                    }
                }
                //释放可能还没释放的进程
                ExcelBook.Close();
                ExcelApp.Quit();
                return sfd.FileName;
            }
            catch
            {
                //System.Windows.MessageBox.Show("导出文件保存失败,可能原因该文件已打开!", "警告!");
                return null;
            }
        }

        /// <summary>
        /// 获取当前列列名,并得到EXCEL中对应的列
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        private string ChangeASC(int count)
        {
            string ascstr = "";
            switch (count)
            {
                case 1:
                    ascstr = "A";
                    break;
                case 2:
                    ascstr = "B";
                    break;
                case 3:
                    ascstr = "C";
                    break;
                case 4:
                    ascstr = "D";
                    break;
                case 5:
                    ascstr = "E";
                    break;
                case 6:
                    ascstr = "F";
                    break;
                case 7:
                    ascstr = "G";
                    break;
                case 8:
                    ascstr = "H";
                    break;
                case 9:
                    ascstr = "I";
                    break;
                case 10:
                    ascstr = "J";
                    break;
                case 11:
                    ascstr = "K";
                    break;
                case 12:
                    ascstr = "L";
                    break;
                case 13:
                    ascstr = "M";
                    break;
                case 14:
                    ascstr = "N";
                    break;
                case 15:
                    ascstr = "O";
                    break;
                case 16:
                    ascstr = "P";
                    break;
                case 17:
                    ascstr = "Q";
                    break;
                case 18:
                    ascstr = "R";
                    break;
                case 19:
                    ascstr = "S";
                    break;
                case 20:
                    ascstr = "T";
                    break;
                default:
                    ascstr = "U";
                    break;
            }
            return ascstr;
        }
        */
    }
}

 

 

posted @ 2019-09-27 09:34  highlightyys  阅读(31)  评论(0)    收藏  举报