我怎么能让我的wpf文本框检索excel中的一些数据

时间:2015-12-02 06:18:29

标签: c# wpf mvvm

我有一个程序,用户将根据excel输入详细信息。如何让我的程序从excel中检索数据..我在谷歌和其他网站上搜索如此努力,并没有找到任何样本.. 方案是用户将在标识符文本框中提供编号,之后程序将根据用户提供的标识符检索excel中的数据..标识符是excel的A列..

的Xaml

    <controls:MetroWindow x:Class='IMDC_ePub_Maker.View.MainView'
                      xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                      xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
                      xmlns:controls='clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro'
                      xmlns:viewModel='clr-namespace:IMDC_ePub_Maker.ViewModel'
                      BorderThickness='1'
                      BorderBrush='#9b7b56'
                      Title='{Binding ProgramExe}'
                      Height='411.445'
                      Width='572.667'
                      ResizeMode="NoResize"
                      WindowStartupLocation="CenterScreen"
                      Closing='MetroWindow_Closing'
                      Icon='/IMDC ePub Maker;component/EPUB-50.png.ico'>
    <controls:MetroWindow.DataContext>
        <viewModel:MainViewModel />
    </controls:MetroWindow.DataContext>
    <UserControl>
        <UserControl.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source='/IMDC ePub Maker;component/Resources/Icons.xaml' />
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </UserControl.Resources>
        <Grid>
            <Grid.Background>
                <ImageBrush ImageSource='C:\Users\Erwin\Downloads\EPUB-100.png'
                            Opacity=".5" />
            </Grid.Background>
            <Image Name="imgLogo"
                   Height="53"
                   HorizontalAlignment="Left"
                   Stretch="Fill"
                   VerticalAlignment="Top"
                   Width="160"
                   Margin="2,5,0,0"
                   Source='D:\Erwin\_Projects\_WPF Apps\DBNL Delivery Details\DBNL Delivery Details\Images\logo.png' />
            <Label Height="28"
                   HorizontalAlignment="Left"
                   Margin="165,19,0,0"
                   VerticalAlignment="Top"
                   FontSize="14"
                   Content="{Binding ProgramName}" />
            <Label Height="28"
                   HorizontalAlignment="Left"
                   Margin="167,37,0,0"
                   VerticalAlignment="Top"
                   FontSize="9"
                   Content="{Binding ProgramVersion}" />
            <GroupBox Header="Input Path"
                      Height="79"
                      HorizontalAlignment="Left"
                      Margin="12,71,0,0"
                      VerticalAlignment="Top"
                      Width="540"
                      IsEnabled="{Binding IsNotBusy}">
                <Grid>
                    <TextBox Height="23"
                             HorizontalAlignment="Left"
                             Margin="6,6,0,0"
                             VerticalAlignment="Top"
                             Width="462"
                             controls:TextBoxHelper.Watermark="Input Files"
                             controls:TextBoxHelper.ClearTextButton="True"
                             Text="{Binding PathM.InputPath, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" />
                    <Button Height="23"
                            HorizontalAlignment="Left"
                            Margin="473,7,0,0"
                            VerticalAlignment="Top"
                            Width="49"
                            Command='{Binding BrowseDirectory}'
                            Opacity=".7">
                        <Rectangle Width='15'
                                   Height='15'
                                   Fill='{DynamicResource BlackBrush}'>
                            <Rectangle.OpacityMask>
                                <VisualBrush Stretch='Fill'
                                             Visual='{StaticResource appbar_folder_open }' />
                            </Rectangle.OpacityMask>
                        </Rectangle>
                    </Button>
                </Grid>
            </GroupBox>
            <GroupBox x:Name='groupBox'
                      Header='ePub Details'
                      HorizontalAlignment='Left'
                      Margin='12,155,0,0'
                      VerticalAlignment='Top'
                      Height='170'
                      Width='540'
                      IsEnabled="{Binding IsNotBusy}">
                <Grid>
                    <ComboBox HorizontalAlignment='Left'
                              VerticalAlignment='Top'
                              Width='250'
                              Margin='268,99,0,0'
                              Height='19'
                              controls:TextBoxHelper.Watermark="Choose Validator"
                              ItemsSource="{Binding EPubM.JavaePubValidatorList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True}"
                              SelectedValue="{Binding EPubM.JavaePubValidator}"
                              Opacity=".8" />
                    <TextBox HorizontalAlignment='Left'
                             Height='23'
                             Margin='10,37,0,0'
                             VerticalAlignment='Top'
                             Width='250'
                             controls:TextBoxHelper.Watermark="Book Title"
                             controls:TextBoxHelper.ClearTextButton="True"
                             Text="{Binding EPubM.BookTitle, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True}"
                             Opacity=".8" />
                    <TextBox HorizontalAlignment='Left'
                             Height='23'
                             Margin='10,68,0,0'
                             VerticalAlignment='Top'
                             Width='250'
                             controls:TextBoxHelper.Watermark="Author"
                             controls:TextBoxHelper.ClearTextButton="True"
                             Text="{Binding EPubM.Author, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True}"
                             Opacity=".8" />
                    <TextBox HorizontalAlignment='Left'
                             Height='23'
                             Margin='10,99,0,0'
                             VerticalAlignment='Top'
                             Width='250'
                             controls:TextBoxHelper.Watermark="Identifier"
                             controls:TextBoxHelper.ClearTextButton="True"
                             Text="{Binding EPubM.Identifier, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True}"
                             Opacity=".8" />
                    <TextBox HorizontalAlignment='Left'
                             Height='23'
                             Margin='268,6,0,0'
                             VerticalAlignment='Top'
                             Width='250'
                             controls:TextBoxHelper.Watermark="ePub Filename"
                             controls:TextBoxHelper.ClearTextButton="True"
                             Text="{Binding EPubM.EpubFileName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True}"
                             Opacity=".8" />
                    <TextBox HorizontalAlignment='Left'
                             Height='23'
                             Margin='268,37,0,0'
                             VerticalAlignment='Top'
                             Width='250
                             '
                             controls:TextBoxHelper.Watermark="Publisher"
                             controls:TextBoxHelper.ClearTextButton="True"
                             Text="{Binding EPubM.Publisher, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True}"
                             Opacity=".8" />
                    <ComboBox HorizontalAlignment='Left'
                              VerticalAlignment='Top'
                              Width='250'
                              Margin='268,68,0,0'
                              Height='19'
                              controls:TextBoxHelper.Watermark="Choose Language"
                              ItemsSource="{Binding EPubM.LanguageList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True}"
                              SelectedValue="{Binding EPubM.Language}"
                              Opacity=".8" />
                    <ComboBox HorizontalAlignment='Left'
                              VerticalAlignment='Top'
                              Width='250'
                              Margin='10,6,0,0'
                              Height='19'
                              controls:TextBoxHelper.Watermark="Choose Project"
                              ItemsSource="{Binding PathM.ProjectList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnDataErrors=True}"
                              SelectedValue="{Binding PathM.Project}"
                              Opacity=".8" />
                </Grid>
            </GroupBox>
            <Button Content="_Process"
                    Height="40"
                    HorizontalAlignment="Left"
                    Margin="454,330,0,0"
                    VerticalAlignment="Top"
                    Width="98"
                    Command="{Binding StartProcess}"
                    IsEnabled="{Binding IsNotBusy}"
                    Opacity=".7" />
            <Label Content='{Binding StatM.ActivityStatus}'
                   HorizontalAlignment='Left'
                   Margin='10,320,0,0'
                   VerticalAlignment='Top'
                   Height='41'
                   Width='343'
                   FontSize="10"
                   FontStyle="Italic" />
            <Label Content='{Binding StatM.DisplayName}'
                   HorizontalAlignment='Left'
                   Margin='10,335,0,0'
                   VerticalAlignment='Top'
                   Height='41'
                   Width='343'
                   FontSize="12"
                   FontWeight="Medium" />
            <controls:MetroProgressBar Height="19"
                                       IsIndeterminate="True"
                                       Margin="16,351,126,10"
                                       Visibility="{Binding StatM.OnOffProgBar}"
                                       Foreground='Brown' />
            <Button HorizontalAlignment='Left'
                    Margin='491,23,0,0'
                    VerticalAlignment='Top'
                    Width='47'
                    Command='{Binding About, Mode=OneWay}'
                    IsEnabled='{Binding IsNotBusy}'
                    Opacity=".7">
                <Rectangle Width='15'
                           Height='15'
                           Fill='{DynamicResource BlackBrush}'>
                    <Rectangle.OpacityMask>
                        <VisualBrush Stretch='Fill'
                                     Visual='{StaticResource appbar_book_perspective_help}' />
                    </Rectangle.OpacityMask>
                </Rectangle>
            </Button>
        </Grid>
    </UserControl>
</controls:MetroWindow>

MainViewModel

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using IMDC_ePub_Maker.Class;
using IMDC_ePub_Maker.Command;
using IMDC_ePub_Maker.Model;
using IMDC_ePub_Maker.Properties;
using IMDC_ePub_Maker.View;
using MessageBox = System.Windows.MessageBox;

namespace IMDC_ePub_Maker.ViewModel
{
    public class MainViewModel : BaseViewModel
    {
        private PathModel _pathM;
        private bool _isNotBusy;
        private DelegateCommand _about;
        private DelegateCommand _browseDirectory;
        private DelegateCommand _startProcess;
        private StatusModel _statM;
        private EPubModel _ePubM;
        private readonly List<ErrorModel> _errorList;
        private readonly List<ErrorModel> _warningList;


        public MainViewModel()
        {
            PathM = new PathModel();
            StatM = new StatusModel();
            EPubM = new EPubModel();
            _warningList = new List<ErrorModel>();
            StatM.OnOffProgBar = Visibility.Hidden;
            StatM.ActivityStatus = "Idle...";
            StatM.DisplayName = "Waiting for input...";
            IsNotBusy = true;
            _errorList = new List<ErrorModel>();
            _warningList = new List<ErrorModel>();
        }

        public PathModel PathM
        {
            get { return _pathM; }
            set { _pathM = value; OnPropertyChanged("PathM"); }
        }

        public StatusModel StatM
        {
            get { return _statM; }
            set { _statM = value; OnPropertyChanged("StatM"); }
        }

        public EPubModel EPubM
        {
            get { return _ePubM; }
            set { _ePubM = value; OnPropertyChanged("EPubM"); }
        }

        public bool IsNotBusy
        {
            get { return _isNotBusy; }
            set { _isNotBusy = value; OnPropertyChanged("IsNotBusy"); }
        }

        public static string ProgDesc => Global.Description;

        public static string ProgramAuthor => Global.Author;

        public static string ProgramExe => Global.ProgramExe + " -- " + Global.ProgramVersion + " (" + Global.ProgramVerDate + ")";

        public static string ProgramName => Global.ProgramName;

        public static string ProgramVersion => (Global.ProgramVersion + " - " + Global.ProgramVerDate);

        public ICommand BrowseDirectory
        {
            get
            {
                _browseDirectory = new DelegateCommand(() =>
                {
                    var dialog = new FolderBrowserDialog
                    {
                        Description = Resources.BrowseDirectory,
                        SelectedPath = AppDomain.CurrentDomain.BaseDirectory
                    };
                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        PathM.InputPath = dialog.SelectedPath;
                    }
                });
                return _browseDirectory;
            }
        }

        public ICommand About
        {
            get
            {
                _about = new DelegateCommand(() =>
                {
                    var about = new About();
                    about.Show();
                });
                return _about;
            }
        }

        public ICommand StartProcess
        {
            get
            {
                _startProcess = new DelegateCommand(() =>
                {
                    if ((PathM.ErrorList.Count > 0) && EPubM.ErrorList.Count > 0) return;
                    if ((string.IsNullOrEmpty(EPubM.JavaePubValidator)) || (string.IsNullOrEmpty(EPubM.Language))) return;
                    var worker = new BackgroundWorker();
                    worker.DoWork += DoWork;
                    worker.RunWorkerCompleted += RunWorkerCompleted;
                    IsNotBusy = false;
                    StatM.OnOffProgBar = Visibility.Visible;
                    try
                    {
                        worker.RunWorkerAsync();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString(), Global.ProgramName, MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                });
                return _startProcess;
            }
        }



        private void DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                StatM.DisplayName = string.Concat(EPubM.EpubFileName, ".epub").Replace("_", "__");
                StatM.ActivityStatus = "I'm working on it...";
                Thread.Sleep(1000);
                if (Directory.Exists(PathModel.OutputPath))
                {
                    DeleteDirectory(PathModel.OutputPath);
                }
                var htmlfiles =
                    new List<string>(Directory.EnumerateFiles(PathM.InputPath, "*.html", SearchOption.TopDirectoryOnly));               
                Global.DocAuthor = EPubM.Author;
                Global.DocTitle = EPubM.BookTitle;
                Global.Language = EPubM.Language;
                Global.Publisher = EPubM.Publisher;
                Global.Identifier = EPubM.Identifier;
                Global.EPubJavaValidator = EPubM.JavaePubValidator;
                Global.EPubName = EPubM.EpubFileName;
                Global.SupportPath = PathModel.SupportPath;
                Global.ValidatorPath = PathModel.ValidatorPath;             
                Global.ImageLoc = PathM.ImagePath;
                Global.InputPath = PathM.InputPath;
                var report = new Report();
                try
                {                   
                    foreach (var html in htmlfiles)
                    {
                        StatM.ActivityStatus = "Checking Garbage Character...";
                        StatM.DisplayName = Path.GetFileName(html)?.Replace("_", "__");
                        CheckGarbageCharacters(html);
                        Thread.Sleep(300);
                        StatM.ActivityStatus = "Checking Multiple spacess...";
                        StatM.DisplayName = Path.GetFileName(html)?.Replace("_", "__");
                        CheckMultipleSpaces(html);
                        Thread.Sleep(300);
                        StatM.ActivityStatus = "Checking Tab Data...";
                        StatM.DisplayName = Path.GetFileName(html)?.Replace("_", "__");
                        CheckTabData(html);
                        Thread.Sleep(300);
                    }
                    if (_errorList.Count <= 0)
                    {
                        Directory.CreateDirectory(PathModel.OutputPath);
                        StatM.ActivityStatus = "Creating ePub...";
                        StatM.DisplayName = string.Concat(EPubM.EpubFileName, ".epub");
                        EPubMaker.CreateEpub(PathM.InputPath, PathModel.OutputPath);
                        CheckCover();
                        if (_warningList.Count > 0)
                        {
                            report.CreateReport(_warningList, Path.Combine(PathModel.OutputPath, string.Concat(EPubM.EpubFileName, ".edt")), PathM.Project);
                        }
                    }
                    else
                    {
                        Directory.CreateDirectory(PathModel.OutputPath);
                        report.CreateReport(_errorList, Path.Combine(PathModel.OutputPath, string.Concat(EPubM.EpubFileName, ".edt")), PathM.Project);
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    Environment.Exit(110);
                }

            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Environment.Exit(110);
            }
        }

        private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            var path = Path.Combine(PathModel.OutputPath, string.Concat("~", EPubM.EpubFileName));
            if (Directory.Exists(Path.Combine(PathModel.OutputPath, string.Concat("~", EPubM.EpubFileName))))
            {
                DeleteDirectory(path);
            }
            ResetValues();
            StatM.OnOffProgBar = Visibility.Hidden;
            IsNotBusy = true;
            StatM.ActivityStatus = "";
            StatM.DisplayName = "Processing Complete!";
        }

        private static void DeleteDirectory(string path)
        {
            foreach (var directory in Directory.GetDirectories(path))
            {
                DeleteDirectory(directory);
            }
            try
            {
                Directory.Delete(path, true);
            }
            catch (IOException)
            {
                Directory.Delete(path, true);
            }
            catch (UnauthorizedAccessException)
            {
                Directory.Delete(path, true);
            }
        }

        private void ResetValues()
        {
            PathM.InputPath = string.Empty;
            EPubM.BookTitle = string.Empty;
            EPubM.Author = string.Empty;
            EPubM.EpubFileName = string.Empty;
            EPubM.Identifier = string.Empty;
            EPubM.JavaePubValidator = string.Empty;
            EPubM.Language = string.Empty;
            EPubM.Publisher = string.Empty;
        }

    }
}

Excel文件

excel

Excel VM

public static DataTable ReadInventory(string excelPath)
    {
        string cmdText = "select * from [Search Result$]";
        string connectionString = "Provider=Microsoft.Jet.OleDb.4.0;\r\n                              Data Source=" + excelPath + ";Extended Properties=Excel 8.0;";
        DataTable table = new DataTable();
        OleDbConnection connection = new OleDbConnection(connectionString);
        OleDbCommand command = null;
        OleDbDataReader reader = null;
        connection.Open();
        try
        {
            command = new OleDbCommand(cmdText, connection);
            reader = command.ExecuteReader();
            table.Load(reader);
        }
        catch (Exception exception)
        {
            throw new Exception(exception.ToString());
        }
        finally
        {
            command.Dispose();
            reader.Dispose();
            connection.Close();
            connection.Dispose();
        }
        return table;
    }

0 个答案:

没有答案