【基於WPF+OneNote+Oracle的中文圖片識別系統階段總結】之篇三:批量處理后的txt文件入庫處理


篇一:WPF常用知識以及本項目設計總結:http://www.cnblogs.com/baiboy/p/wpf.html

篇二:基於OneNote難點突破和批量識別:http://www.cnblogs.com/baiboy/p/wpf1.html

篇三:批量處理后的txt文件入庫處理:http://www.cnblogs.com/baiboy/p/wpf2.html

篇四:關於OneNote入庫處理以及審核:http://www.cnblogs.com/baiboy/p/wpf3.html


【小記】:大膽嘗試才能突破,某個中醫葯大學有一批圖片需要處理(ORC),然后進行數據挖掘。之前沒有接觸過ORC這個東西,但是還是應允了。在網上搜索一番,關於中文圖片識別,最終敲定為基於微軟的OneNote,其識別率相對較高。網上這個技術點的資料真心不多,后來於博客園找到一篇博文,但是那個程序還是bug百出,而且只是單處理。后來經過一番摸索逐個突破,批處理完成。然后進行界面設計,這些零碎工作完成后,便是入庫處理。由於OneNote生成的xml文件封裝好的,即不可視的。便將其代碼處理生成txt文件,再進行Oracle入庫處理。入庫前需要文件內容審核,並且在WPF開發中數據綁定和分頁中做了獨特處理。現在經過半個月的工作,本項目做個階段總結。一則知識總結便於二次開發,盡量保持程序流暢性,核心知識做以梳理;另外,相關WPFOneNote常用技術共享,便於部分園友所需。本人技術有限,歡迎交流。項目還未結束,暫作階段文章發布,隨后相繼發布。


篇三:批量處理后的txt文件入庫處理

【開篇概述】:本文繼上述文章再做深度剖析,本篇主要介紹txt入庫(oracle)和wpf分頁,在此篇涉及的頁面設計前篇已經細述不再概說。里面涉及到oracle 64位系統安裝處理問題,以前oracle的表,序列,觸發器,自增種子等基本操作。外加文件操作和利用用戶控件分頁等技術。大致效果圖如下,其次粘貼完整代碼,其后就一一概說本文核心要點和難點突破,最后梳理技術知識點,使其一則保持完整性,二則梳理整理知識點便於隨時取用。(本篇暫做效果圖如下,至於最終效果圖和審核界面,待終篇。)

效果圖:

 

完整代碼:

namespace OnenoteOCRDemo { /// <summary> /// TextData.xaml 的交互邏輯 /// </summary> public partial class TextData : Window { public TextData() { InitializeComponent(); this.Loaded += new RoutedEventHandler(MainWindow_Loaded); } void MainWindow_Loaded(object sender, RoutedEventArgs e) { this.Loaded += delegate { InitData(); }; dataGrid1.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid1_LoadingRow); } void dataGrid1_LoadingRow(object sender, DataGridRowEventArgs e) { e.Row.Header = e.Row.GetIndex() + 1; //設置行表頭的內容值  } //查詢 private void InitData() { string sql = "select * from T_TCM_THESIS order by ID desc"; DataSet ds = MYHelper.SQLHelper.GetOrlData(sql); if (ds.Tables[0].Rows.Count > 0) { page1.ShowPages(this.dataGrid1, ds, 10); } else { System.Windows.Forms.MessageBox.Show("Erroy"); } } private void Window_Loaded(object sender, RoutedEventArgs e) { InitData(); } //批量刪除 List<int> selectFID = new List<int>(); private void CheckBox_Click(object sender, RoutedEventArgs e) { System.Windows.Controls.CheckBox dg = sender as System.Windows.Controls.CheckBox; int FID = int.Parse(dg.Tag.ToString()); //獲取該行的FID var bl = dg.IsChecked; if (bl == true) { selectFID.Add(FID); //如果選中就保存FID  } else { selectFID.Remove(FID); //如果選中取消就刪除里面的FID  } } private void btnDelete_Click(object sender, RoutedEventArgs e) { foreach (int FID in selectFID) { string sql = "delete T_TCM_THESIS where id=" + FID; int i = SQLHelper.OrlExecuteQuery(sql); if (i > 0) { System.Windows.Forms.MessageBox.Show("success!!!"); } else { System.Windows.Forms.MessageBox.Show("Erroy!!!"); } InitData(); } } public void TextIsNull() { txtdocname.Text = ""; txtyears.Text = ""; txtdoctype.Text = ""; txtsummary.Text = ""; txtauthor.Text = ""; txtsource.Text = ""; txtsourcetype.Text = ""; txtmemo.Text = ""; txttitle.Text = ""; txtenglishtitle.Text = ""; txtcompany.Text = ""; txtkeyword.Text = ""; txtcontent.Text = ""; txtdigest.Text = ""; txtpath.Text = ""; txtdisease.Text = ""; } private void btnAdd_Click(object sender, RoutedEventArgs e) { string docname = txtdocname.Text.ToString(); string years = txtyears.Text.ToString(); string doctype = txtdoctype.Text.ToString(); string summary = txtsummary.Text.ToString(); string author = txtauthor.Text.ToString(); string source = txtsource.Text.ToString(); string sourcetype = txtsourcetype.Text.ToString(); string memo = txtmemo.Text.ToString(); string title = txttitle.Text.ToString(); string englishtitle = txtenglishtitle.Text.ToString(); string authorcompany = txtcompany.Text.ToString(); string keyword = txtkeyword.Text.ToString(); string content = txtcontent.Text.ToString().Trim(); string digest = txtdigest.Text.ToString(); string path = txtpath.Text.ToString(); string disease = txtdisease.Text.ToString(); int auditflag = 1; try { string sql = "INSERT INTO T_TCM_THESIS(docname,years,doctype,summary,author,source,sourcetype,memo,title,englishtitle,"; sql += "authorcompany,keyword,content,digest,path,disease,auditflag) Values('" + docname + "','" + years + "','" + doctype + "','" + summary + "',"; sql += "'" + author + "','" + source + "','" + sourcetype + "','" + memo + "','" + title + "','" + englishtitle + "','" + authorcompany + "','" + keyword + "',"; sql += "'" + content + "','" + digest + "','" + path + "','" + disease + "'," + auditflag + ")"; int i = SQLHelper.OrlExecuteQuery(sql); if (i > 0) { System.Windows.Forms.MessageBox.Show("success!!!"); TextIsNull(); } else { System.Windows.Forms.MessageBox.Show("Erroy!!!"); } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } InitData(); } //選擇入庫文本 private void bnt_Click(object sender, RoutedEventArgs e) { txtcontent.Text = ""; openData1(); } //入庫文本操作  } }
View Code

 


【功能以及操作描述】

  1. 首先要安裝oracle數據庫,當然安裝過后可以跳過第一步,沒有的話,我重點介紹下64位oracle安裝情況,因為中間有一些問題需要解決。64位系統中PL/SQL不能連接數據庫,解決的文章偏多,建議參看此篇博文:http://blog.sina.com.cn/s/blog_475839a50101hoyg.html。在完成oracle安裝后可以做具體表的設計等,后面展開。  
  2. 在本頁面,用戶選擇瀏覽選擇對應的文件,通過流讀取,利用正則表達式截取核心字段數據。因為文本中包含書名/作者/題目等信息,為了體現用戶友好性,則做如下操作:(由於截取時的標准不一,可能有所錯誤,故另加審核頁面。 )
                        StreamReader sr = new StreamReader(ofd.FileName, System.Text.Encoding.Default);
                        txtcontent.Text += sr.ReadToEnd();
                        sr.Close();
                        //指定截取書名
                        string str_start = @"書名:(?<info>\w[^。|,^.|^,|^:|^:]+)";//可剔除后邊的中英文逗號,句號等
                        Regex MyRegex = new Regex(str_start, RegexOptions.Multiline);
                        string a = txtcontent.Text;
                        Match MyMatch = MyRegex.Match(a);
                        txttitle.Text=txtdocname.Text = MyMatch.Groups["info"].Value.ToString();
                        //指定截取作者
                        string str_start1 = @"作者:(?<info>\w[^。|,^.|^,|^:|^:]+)";//可剔除后邊的中英文逗號,句號等
                        Regex MyRegex1 = new Regex(str_start1, RegexOptions.Multiline);
                        string b = txtcontent.Text;
                        Match MyMatch1 = MyRegex1.Match(b);
                        txtauthor.Text = MyMatch1.Groups["info"].Value.ToString();
                        //指定截取朝代
                        string str_start2 = @"朝代:(?<info>\w[^。|,^.|^,|^:|^:]+)";//可剔除后邊的中英文逗號,句號等
                        Regex MyRegex2 = new Regex(str_start2, RegexOptions.Multiline);
                        string c = txtcontent.Text;
                        Match MyMatch2 = MyRegex2.Match(c);
                        txtyears.Text = MyMatch2.Groups["info"].Value.ToString();
    View Code
  3. 通過點擊添加按鈕,進行入庫,入庫后通過審核再做修改。
    private void btnAdd_Click(object sender, RoutedEventArgs e)
            {
                string docname = txtdocname.Text.ToString();
                string years = txtyears.Text.ToString();
                string doctype = txtdoctype.Text.ToString();
                string summary = txtsummary.Text.ToString();
                string author = txtauthor.Text.ToString();
                string source = txtsource.Text.ToString();
                string sourcetype = txtsourcetype.Text.ToString();
                string memo = txtmemo.Text.ToString();
                string title = txttitle.Text.ToString();
                string englishtitle = txtenglishtitle.Text.ToString();
                string authorcompany = txtcompany.Text.ToString();
                string keyword = txtkeyword.Text.ToString();
                string content = txtcontent.Text.ToString().Trim();
                string digest = txtdigest.Text.ToString();
                string path = txtpath.Text.ToString();
                string disease = txtdisease.Text.ToString();
                int auditflag = 1;
                try
                {
                    string sql = "INSERT INTO T_TCM_THESIS(docname,years,doctype,summary,author,source,sourcetype,memo,title,englishtitle,";
                    sql += "authorcompany,keyword,content,digest,path,disease,auditflag) Values('" + docname + "','" + years + "','" + doctype + "','" + summary + "',";
                    sql += "'" + author + "','" + source + "','" + sourcetype + "','" + memo + "','" + title + "','" + englishtitle + "','" + authorcompany + "','" + keyword + "',";
                    sql += "'" + content + "','" + digest + "','" + path + "','" + disease + "'," + auditflag + ")";
                    int i = SQLHelper.OrlExecuteQuery(sql);
                    if (i > 0)
                    {
                        System.Windows.Forms.MessageBox.Show("success!!!");
                        TextIsNull();
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("Erroy!!!");
                    }
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message);
                }
                InitData();
            }
    View Code
  4. 在DataGrid中復選框中綁定主建,進行批量刪除操作等。(樣式設計不同winform或web中涉及,需要樣式綁定,參照篇一)
    //批量刪除
            List<int> selectFID = new List<int>();  
    
            private void CheckBox_Click(object sender, RoutedEventArgs e)
            {
                System.Windows.Controls.CheckBox dg = sender as System.Windows.Controls.CheckBox;
                int FID = int.Parse(dg.Tag.ToString());   //獲取該行的FID   
                var bl = dg.IsChecked;
                if (bl == true)
                {
                    selectFID.Add(FID);         //如果選中就保存FID   
                }
                else
                {
                    selectFID.Remove(FID);  //如果選中取消就刪除里面的FID   
                }  
               
            }
    
            private void btnDelete_Click(object sender, RoutedEventArgs e)
            {
                foreach (int FID in selectFID)
                {
                    string sql = "delete  T_TCM_THESIS where id=" + FID;
                    int i = SQLHelper.OrlExecuteQuery(sql);
                    if (i > 0)
                    {
                        System.Windows.Forms.MessageBox.Show("success!!!");
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("Erroy!!!");
                    }
                    InitData();
                }  
            }
    View Code
  5. 最后完成分頁,數據分頁在list列表存儲時,通過集合的方法傳參容易解決,網上相關分頁較多,但是連接數據庫分頁,比較麻煩。本人查找很多資料,最后選擇用戶控件分頁處理(page.xaml)。(用戶控件分頁已是完整操作,需要直接引用即可,隨后粘貼完整代碼。)
  • 用戶控件前台設計:
    <UserControl x:Class="OnenoteOCRDemo.page"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 mc:Ignorable="d" >
           <UserControl.Resources>
        <!--每頁{0}/共{0}條-->
        <Style x:Key="PageTextBlock1" TargetType="{x:Type TextBlock}">
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="HorizontalAlignment" Value="Left" />
            <Setter Property="FontSize" Value="13" />
            <Setter Property="FontWeight" Value="Bold" />
            <Setter Property="Foreground" Value="White" />
        </Style>
        <!--首頁上一頁等-->
        <Style x:Key="PageTextBlock2" TargetType="{x:Type TextBlock}">
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="HorizontalAlignment" Value="Left" />
            <Setter Property="Margin" Value="0,10,0,0" />
            <Setter Property="Width" Value="40" />
            <Setter Property="Height" Value="23" />
            <Setter Property="FontSize" Value="13" />
            <Setter Property="Cursor" Value="Hand" />
            <Setter Property="Foreground" Value="White" />
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="#FF000000" />
                    <Setter Property="FontWeight" Value="Bold" />
                </Trigger>
            </Style.Triggers>
        </Style>
        <!--中間頁數-->
        <Style x:Key="PageTextBlock3" TargetType="{x:Type TextBlock}">
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="HorizontalAlignment" Value="Left" />
            <Setter Property="Margin" Value="0,10,0,0" />
            <Setter Property="Height" Value="23" />
            <Setter Property="Width" Value="30" />
            <Setter Property="FontSize" Value="10" />
            <Setter Property="Cursor" Value="Hand" />
            <Setter Property="Foreground" Value="White" />
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="#FF000000" />
                    <Setter Property="FontWeight" Value="Bold" />
                </Trigger>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Foreground" Value="#FF000000" />
                    <Setter Property="FontWeight" Value="Bold" />
                </Trigger>
            </Style.Triggers>
        </Style>
        <Style x:Key="PageTextBox" TargetType="{x:Type TextBox}">
            <Setter Property="Height" Value="25" />
            <Setter Property="Width" Value="40" />
            <Setter Property="BorderBrush" Value="{x:Null}" />
            <Setter Property="HorizontalAlignment" Value="Left" />
            <Setter Property="VerticalAlignment" Value="Bottom" />
            <Setter Property="Background">
                <Setter.Value>
                        <ImageBrush ImageSource="/OnenoteOCRDemo;component/Images/Page_TextBack.png" ></ImageBrush>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsReadOnly" Value="True">
                    <Setter Property="Background" Value="White" />
                </Trigger>
            </Style.Triggers>
        </Style>
        <Style x:Key="PageButton" TargetType="{x:Type Button}">
            <Setter Property="Height" Value="25" />
            <Setter Property="Width" Value="30" />
            <Setter Property="Foreground" Value="White" />
            <Setter Property="HorizontalAlignment" Value="Left" />
            <Setter Property="VerticalAlignment" Value="Bottom" />
        </Style>
        </UserControl.Resources>
        <Grid HorizontalAlignment="Left" Height="30" Width="1024">
            <Grid.Background>
                <ImageBrush ImageSource="style\b2.png" Stretch="Fill"/>
            </Grid.Background>
            <Border CornerRadius="3"   BorderBrush="{x:Null}">
              
                <Grid HorizontalAlignment="Stretch" Margin="5 0 5 0"  VerticalAlignment="Top" Width="Auto" Height="30">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="150"/>
                        <ColumnDefinition Width="600*" MinWidth="600"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Name="tbkRecords" Grid.Column="0" Style="{StaticResource PageTextBlock1}" />
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Grid.Column="1">
                        <Grid>
                            <Grid.RowDefinitions >
                                <RowDefinition Height="30"></RowDefinition>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="50"/>
                                <ColumnDefinition Width="50"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="50"/>
                                <ColumnDefinition Width="50"/>
                                <ColumnDefinition Width="50"/>
                                <ColumnDefinition Width="30"/>
                            </Grid.ColumnDefinitions>
                            <TextBlock Grid.Column="0" Name="btnFirst" Text="首頁" IsEnabled="False" Style="{StaticResource PageTextBlock2}" />
                            <TextBlock Grid.Column="1" Name="btnPrev" Text="上一頁" IsEnabled="False" Style="{StaticResource PageTextBlock2}" />
                            <Grid Grid.Column="2" Name="grid" >
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="30" ></RowDefinition>
                                </Grid.RowDefinitions>
                            </Grid>
                            <TextBlock Foreground="White" Grid.Column="3" Name="btnNext" Text="下一頁" IsEnabled="False" Style="{StaticResource PageTextBlock2}" />
                            <TextBlock Grid.Column="4" Name="btnLast" Text="未頁" IsEnabled="False" Style="{StaticResource PageTextBlock2}"/>
                            <TextBox Grid.Column="5" Name="pageGo" MaxLength="6" IsReadOnly="True" Style="{StaticResource PageTextBox}" />
                            <Button Grid.Column="6" Name="btnGo" Content="GO" IsEnabled="False" Style="{StaticResource PageButton}" />
                        </Grid>
                    </StackPanel>
                </Grid>
            </Border>
        </Grid>
    </UserControl>
    View Code

     

  • 用戶空間后台源碼:
    namespace OnenoteOCRDemo
    {
        /// <summary>
        /// page.xaml 的交互邏輯
        /// </summary>
        public partial class page : UserControl
        {
            public page()
            {
                InitializeComponent();
                this.Loaded += delegate
                {
                    this.btnFirst.MouseLeftButtonUp += new MouseButtonEventHandler(btnFirst_Click);
                    this.btnPrev.MouseLeftButtonUp += new MouseButtonEventHandler(btnPrev_Click);
                    this.btnNext.MouseLeftButtonUp += new MouseButtonEventHandler(btnNext_Click);
                    this.btnLast.MouseLeftButtonUp += new MouseButtonEventHandler(btnLast_Click);
                    this.btnGo.Click += new RoutedEventHandler(btnGo_Click);
                };
            }
            private DataTable _dt = new DataTable();
            //每頁顯示多少條
            private int pageNum = 10;
            //當前是第幾頁
            private int pIndex = 1;
            //對象
            private DataGrid grdList;
            //最大頁數
            private int MaxIndex = 1;
            //一共多少條
            private int allNum = 0;
    
            #region 初始化數據
            /// <summary>
            /// 初始化數據
            /// </summary>
            /// <param name="grd"></param>
            /// <param name="dtt"></param>
            /// <param name="Num"></param>
            public void ShowPages(DataGrid grd, DataSet ds, int Num)
            {
                if (ds == null || ds.Tables.Count == 0)
                    return;
                if (ds.Tables[0].Rows.Count == 0)
                    return;
                DataTable dt = ds.Tables[0];
                this._dt = dt.Clone();
                this.grdList = grd;
                this.pageNum = Num;
                this.pIndex = 1;
                foreach (DataRow r in dt.Rows)
                    this._dt.ImportRow(r);
                SetMaxIndex();
                ReadDataTable();
                if (this.MaxIndex > 1)
                {
                    this.pageGo.IsReadOnly = false;
                    this.btnGo.IsEnabled = true;
                }
            }
            #endregion
    
            #region 畫數據
            /// <summary>
            /// 畫數據
            /// </summary>
            private void ReadDataTable()
            {
                try
                {
                    DataTable tmpTable = new DataTable();
                    tmpTable = this._dt.Clone();
                    int first = this.pageNum * (this.pIndex - 1);
                    first = (first > 0) ? first : 0;
                    //如何總數量大於每頁顯示數量
                    if (this._dt.Rows.Count >= this.pageNum * this.pIndex)
                    {
                        for (int i = first; i < pageNum * this.pIndex; i++)
                            tmpTable.ImportRow(this._dt.Rows[i]);
                    }
                    else
                    {
                        for (int i = first; i < this._dt.Rows.Count; i++)
                            tmpTable.ImportRow(this._dt.Rows[i]);
                    }
                    this.grdList.ItemsSource = tmpTable.DefaultView;
                    tmpTable.Dispose();
                }
                catch
                {
                    MessageBox.Show("錯誤");
                }
                finally
                {
                    DisplayPagingInfo();
                }
    
            }
            #endregion
    
            #region 畫每頁顯示等數據
            /// <summary>
            /// 畫每頁顯示等數據
            /// </summary>
            private void DisplayPagingInfo()
            {
                if (this.pIndex == 1)
                {
                    this.btnPrev.IsEnabled = false;
                    this.btnFirst.IsEnabled = false;
                }
                else
                {
                    this.btnPrev.IsEnabled = true;
                    this.btnFirst.IsEnabled = true;
                }
                if (this.pIndex == this.MaxIndex)
                {
                    this.btnNext.IsEnabled = false;
                    this.btnLast.IsEnabled = false;
                }
                else
                {
                    this.btnNext.IsEnabled = true;
                    this.btnLast.IsEnabled = true;
                }
                this.tbkRecords.Text = string.Format("每頁{0}條/共{1}條", this.pageNum, this.allNum);
                int first = (this.pIndex - 4) > 0 ? (this.pIndex - 4) : 1;
                int last = (first + 9) > this.MaxIndex ? this.MaxIndex : (first + 9);
                this.grid.Children.Clear();
                for (int i = first; i <= last; i++)
                {
                    ColumnDefinition cdf = new ColumnDefinition();
                    this.grid.ColumnDefinitions.Add(cdf);
                    TextBlock tbl = new TextBlock();
                    tbl.Text = i.ToString();
                    tbl.Style = FindResource("PageTextBlock3") as Style;
                    tbl.MouseLeftButtonUp += new MouseButtonEventHandler(tbl_MouseLeftButtonUp);
                    if (i == this.pIndex)
                        tbl.IsEnabled = false;
                    Grid.SetColumn(tbl, this.grid.ColumnDefinitions.Count - 1);
                    Grid.SetRow(tbl, 0);
                    this.grid.Children.Add(tbl);
                }
            }
            #endregion
    
            #region 首頁
            /// <summary>
            /// 首頁
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnFirst_Click(object sender, System.EventArgs e)
            {
                this.pIndex = 1;
                ReadDataTable();
            }
            #endregion
    
            #region 上一頁
            /// <summary>
            /// 上一頁
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnPrev_Click(object sender, System.EventArgs e)
            {
                if (this.pIndex <= 1)
                    return;
                this.pIndex--;
                ReadDataTable();
            }
            #endregion
    
            #region 下一頁
            /// <summary>
            /// 下一頁
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnNext_Click(object sender, System.EventArgs e)
            {
                if (this.pIndex >= this.MaxIndex)
                    return;
                this.pIndex++;
                ReadDataTable();
            }
            #endregion
    
            #region 未頁
            /// <summary>
            /// 未頁
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnLast_Click(object sender, System.EventArgs e)
            {
                this.pIndex = this.MaxIndex;
                ReadDataTable();
            }
            #endregion
    
            #region 設置最多大頁面
            /// <summary>
            /// 設置最多大頁面
            /// </summary>
            private void SetMaxIndex()
            {
                //多少頁
                int Pages = this._dt.Rows.Count / pageNum;
                if (this._dt.Rows.Count != (Pages * pageNum))
                {
                    if (_dt.Rows.Count < (Pages * pageNum))
                        Pages--;
                    else
                        Pages++;
                }
                this.MaxIndex = Pages;
                this.allNum = this._dt.Rows.Count;
            }
            #endregion
    
            #region 跳轉到多少頁
            /// <summary>
            /// 跳轉到多少頁
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnGo_Click(object sender, RoutedEventArgs e)
            {
                if (IsNumber(this.pageGo.Text))
                {
                    int pageNum = int.Parse(this.pageGo.Text);
                    if (pageNum > 0 && pageNum <= this.MaxIndex)
                    {
                        this.pIndex = pageNum;
                        ReadDataTable();
                    }
                    else if (pageNum > this.MaxIndex)
                    {
                        this.pIndex = this.MaxIndex;
                        ReadDataTable();
                    }
                }
                this.pageGo.Text = "";
            }
            #endregion
    
            private void tbl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            {
                TextBlock tbl = sender as TextBlock;
                if (tbl == null)
                    return;
                int index = int.Parse(tbl.Text.ToString());
                this.pIndex = index;
                if (index > this.MaxIndex)
                    this.pIndex = this.MaxIndex;
                if (index < 1)
                    this.pIndex = 1;
                ReadDataTable();
            }
    
            private static Regex RegNumber = new Regex("^[0-9]+$");
    
    
            #region 判斷是否是數字
            /// <summary>
            /// 判斷是否是數字
            /// </summary>
            /// <param name="valString"></param>
            /// <returns></returns>
            public static bool IsNumber(string valString)
            {
                Match m = RegNumber.Match(valString);
                return m.Success;
            }
            #endregion
        }
    }
    View Code

    完成以上操作,然后再mian.xaml需要引用用戶頁面添加如下代碼:在window中xmlns:my="clr-namespace:OnenoteOCRDemo"和在grid中<my:page  x:Name="page1" Height="30" VerticalAlignment="Top"></my:page>


【所遇問題以及瓶頸突破】

  1. 使用 64位 win8 /win7系統+64位 oracle+PL/SQL處理,如果是32位較流暢,只是64位系統中不支持64位PL/SQL,需要下載32位PL/SQL做置。 
    注:問題詳解參照http://blog.sina.com.cn/s/blog_475839a50101hoyg.html即可。

     

  2. oracle設計表時候如何才能像sql server那樣直接配置主鍵種子自增?其通過創建序列,然后通過觸發器實現。                                                                      
    /*創建數據庫表*/
    create table T_TCM_THESIS  (
       ID                   NUMBER                          not null,
       DOCNAME              VARCHAR2(512),
       YEARS                VARCHAR2(128),
       DOCTYPE              VARCHAR2(128),
       SUMMARY              VARCHAR2(4000),
       AUTHOR               VARCHAR2(128),
       SOURCE               VARCHAR2(2048),
       SOURCETYPE           VARCHAR2(128),
       MEMO                 VARCHAR2(1024),
       TITLE                VARCHAR2(512),
       ENGLISHTITLE         VARCHAR2(512),
       AUTHORCOMPANY        VARCHAR2(512),
       KEYWORD              VARCHAR2(512),
       CONTENT              CLOB,
       DIGEST               VARCHAR2(4000),
       PATH                 VARCHAR2(256),
       DISEASE              VARCHAR2(256),
       AUDITFLAG            NUMBER(1),
       constraint PK_TZJ_PINTOOL_THESIS primary key (ID)
    );
    /*字段的注解*/
    comment on table T_TCM_THESIS is
    '中醫文獻表';
    
    comment on column T_TCM_THESIS.ID is
    '編號';
    
    comment on column T_TCM_THESIS.DOCNAME is
    '文獻名';
    
    comment on column T_TCM_THESIS.YEARS is
    '年代';
    
    comment on column T_TCM_THESIS.DOCTYPE is
    '文獻類型';
    
    comment on column T_TCM_THESIS.SUMMARY is
    '內容提要';
    
    comment on column T_TCM_THESIS.AUTHOR is
    '作者';
    
    comment on column T_TCM_THESIS.SOURCE is
    '文獻出處';
    
    comment on column T_TCM_THESIS.SOURCETYPE is
    '文獻出處類型';
    
    comment on column T_TCM_THESIS.MEMO is
    '備注';
    
    comment on column T_TCM_THESIS.TITLE is
    '標題';
    
    comment on column T_TCM_THESIS.ENGLISHTITLE is
    '英文標題';
    
    comment on column T_TCM_THESIS.AUTHORCOMPANY is
    '著者單位';
    
    comment on column T_TCM_THESIS.KEYWORD is
    '關鍵詞';
    
    comment on column T_TCM_THESIS.CONTENT is
    '文獻內容';
    
    comment on column T_TCM_THESIS.DIGEST is
    '摘要';
    
    comment on column T_TCM_THESIS.PATH is
    '文獻內容文本文件';
    
    comment on column T_TCM_THESIS.DISEASE is
    '相關病名';
    
    
    comment on column T_TCM_THESIS.AUDITFLAG is
    '是否審核';
    select * from T_TCM_THESIS;
    --------------------------------------------------------------------------------------------------------
    /*以下代碼完成自增*/
    ---------------------------------------------------------------------------------------------------------
    /*創建序列*/
    
    CREATE SEQUENCE EMP_SEQUENCE
      INCREMENT BY 1               -- 每次加幾個
      START WITH 1                 -- 從1開始計數
      NOMAXVALUE                   -- 不設置最大值
      NOCYCLE                      -- 一直累加,不循環
      NOCACHE                      -- 不建緩沖區
    /*創建觸發器*/
     create or replace trigger   TR_EXA  
     before insert on  T_TCM_THESIS for each row             
     begin   
      select   to_char(EMP_SEQUENCE.nextval)   into   :new.id  from   dual;   
     end   TR_EXA;  
    
    /*插入數據,表中18字段,插入時只需填寫17字段。主鍵ID自增*/
    INSERT INTO T_TCM_THESIS(docname,years,doctype,summary,author,source,sourcetype,memo,title,englishtitle,authorcompany,keyword,content,digest,path,disease,auditflag) 
    Values('aa','aa','aa','aa','aa','aa','aa','aa','aa','aa','aa','aa','aa','aa','aa','aa',1);
    /*查詢*/
    select * from T_TCM_THESIS;
    View Code

     

  3. 在VS中完成數據庫連接時候,需要引用oracle的dll組件(32/64)。

      

    注:首先下載System.Data.OracleClient.zip,解壓后有X64/X86文件夾區別,針對自己情況不同做以選擇。然后打開X64/X86文件夾選擇對應的dll組件放在C盤window下,
    然后打開項目-〉引用->瀏覽->選擇確定即可。

                                                                                                              

  4. 如何使用分頁操作?
    注:wpf之前所做小程序,數據大多放在xml等小型數據庫,通過操作list集合調用其方面傳參(每頁顯示,總條數)等完成分頁,這樣方案網上很多。但是通過連接數據庫去處理較為麻煩
    ,我找了很多資料,比較分析后發現利用用戶控件完成分頁,一則調用方面不用任何修改,二則便於操作,功能完善。(代碼參照上面功能以及操作描述)

                                                                                                                                                                          


【核心功能梳理和總結】

  • 用戶控件的創建與使用?
  • 注:1,打開項目-〉添加-〉新建項-〉用戶控件-〉引用頁面中添加xmlns:my="clr-namespace:新建項項目名稱"-〉在grid中<my:新建項名稱  x:Name="page1" Height="30" VerticalAlignment="Top"></my:page>
  • 如何設置表頭內容值?
  • 注:
            void MainWindow_Loaded(object sender, RoutedEventArgs e)
            {
                this.Loaded += delegate
                {
                    InitData();
                };
                dataGrid1.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid1_LoadingRow);
            }
            void dataGrid1_LoadingRow(object sender, DataGridRowEventArgs e)
            {
                e.Row.Header = e.Row.GetIndex() + 1;    //設置行表頭的內容值   
            }

     

  • SQLHelper類的使用,以及完整代碼?
  • 注:這個類可以實現oracle數據庫連接和server數據庫連接,也可以完成參數化sql文本或者存儲過程。很好用,平常自己做項目大多使用此類。
    namespace MYHelper
    {
        //不加public,只有dal私有引用;
        //封裝執行sql server增刪改查輔助類,提供相應執行sql語句和存儲過程的方法
        static class SQLHelper
        {
            //讀取配置文件中的連接字符串
           // static string connstr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString;
            static string connstr = "data source=ORCL;User Id=system;Password=orcl";
            public static DataSet GetOrlData(string sql)
            {
                DataSet ds = new DataSet();
                using (OracleConnection conn = new OracleConnection(connstr))
                {
                    using (OracleCommand cmd = new OracleCommand(sql, conn))
                    {
                        //根據傳來的參數。決定是sql語句還是存儲過程
                        //cmd.CommandType = CommandType.StoredProcedure;
                        conn.Open();
                        using (OracleDataAdapter sda = new OracleDataAdapter(cmd))
                        {
                            sda.Fill(ds);
                        }
                    }
                }
                return ds;
            }
    
            public static int OrlExecuteQuery(string sql)
            {
                int res = -1;
                using (OracleConnection conn = new OracleConnection(connstr))
                {
                    using (OracleCommand cmd = new OracleCommand(sql, conn))
                    {
                        conn.Open();
                        res = cmd.ExecuteNonQuery();
                    }
                }
                return res;
            }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
            /// <summary>
            /// 執行非查詢sql語句,返回受影響行數,如果執行非增刪改則返回-1
            /// </summary>
            /// <param name="sql">sql語句</param>
            /// <param name="paras">參數數組</param>
            /// <returns>影響行數res</returns>
            public static int ExecuteNonQuery(string sql, params SqlParameter[] paras)
            {
                int res = -1;
                using (SqlConnection conn = new SqlConnection(connstr))
                {
                    using (SqlCommand cmd = new SqlCommand(sql, conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        if (paras != null || paras.Length > 0)
                        {
                            cmd.Parameters.AddRange(paras);
                        }
                        conn.Open();
                        res = cmd.ExecuteNonQuery();
                    }
                }
                return res;
            }
    
             public static int ExecuteNonParaQuery(string sql)
             {
                 int res = -1;
                 using (SqlConnection conn = new SqlConnection(connstr))
                 {
                     using (SqlCommand cmd = new SqlCommand(sql, conn))
                     {
                         conn.Open();
                         res = cmd.ExecuteNonQuery();
                     }
                 }
                 return res;
             }
             /// <summary>
             /// 執行讀取數據,返回一個對象
             /// </summary>
             /// <param name="sql">sql語句</param>
             /// <param name="paras">參數數組</param>
             /// <returns>返回一個對象o</returns>
             public static object ExecuteScalar(string sql, params SqlParameter[] paras)
             {
                 object  o = null;
                 using (SqlConnection conn = new SqlConnection(connstr))
                 {
                     using (SqlCommand cmd = new SqlCommand(sql, conn))
                     {
                         cmd.CommandType = CommandType.StoredProcedure;
                         if (paras != null)
                         {
                             cmd.Parameters.AddRange(paras);
                         }
                         conn.Open();
                         o = cmd.ExecuteScalar();
                     }
                 }
                 return o;
             }
             /// <summary>
             /// 執行查詢sql語句,返回一個對象
             /// </summary>
             /// <param name="sql">sql語句</param>
             /// <param name="paras">查詢參數</param>
             /// <returns>返回DataReader對象</returns>
             public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] paras)
             {
                 SqlConnection conn = new SqlConnection(connstr);
                 using (SqlCommand cmd = new SqlCommand(sql, conn))
                 {
                     cmd.CommandType = CommandType.StoredProcedure;
                     if (paras != null)
                     {
                         cmd.Parameters.AddRange(paras);
                     }
                     conn.Open();
                     try
                     {
                         return cmd.ExecuteReader(CommandBehavior.CloseConnection);
                     }
                     catch (Exception ex)
                     {
                         cmd.Dispose();
                         throw ex;
                     }
                 }
             }
    
             /// <summary>
             /// 執行查詢sql語句,返回一個無參數dataset對象
             /// </summary>
             /// <param name="sql">sql語句</param>
             /// <param name="paras"></param>
             /// <returns>返回dataset 對象</returns>
             public static DataSet GetDataSetNotPara(string sql)
             {
                 DataSet ds = new DataSet();
                 using (SqlConnection conn = new SqlConnection(connstr))
                 {
                     using (SqlCommand cmd = new SqlCommand(sql, conn))
                     {
                         //根據傳來的參數。決定是sql語句還是存儲過程
                         cmd.CommandType = CommandType.StoredProcedure;
                         conn.Open();
                         using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                         {
                             sda.Fill(ds);
                         }
                     }
                 }
                 return ds;
             }
             /// <summary>
             /// 執行查詢sql語句,返回一個無參數dataset對象
             /// </summary>
             /// <param name="sql">sql語句</param>
             /// <param name="paras"></param>
             /// <returns>返回dataset 對象</returns>
             public static DataTable  GetDataTableNotPara(string sql)
             {
                 DataTable dt = new DataTable();
                 using (SqlConnection conn = new SqlConnection(connstr))
                 {
                     using (SqlCommand cmd = new SqlCommand(sql, conn))
                     {
                         //根據傳來的參數。決定是sql語句還是存儲過程
                      
                         conn.Open();
                         using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                         {
                             sda.Fill(dt);
                         }
                     }
                 }
                 return dt;
             }
    
             /// <summary>
             /// 執行查詢sql語句,返回一個dataset對象
             /// </summary>
             /// <param name="sql">sql語句</param>
             /// <param name="paras">查詢參數</param>
             /// <returns>返回dataset 對象</returns>
             public static DataSet GetDataSet(string sql, params SqlParameter[] paras)
             {
                 DataSet  ds = new DataSet();
                 using (SqlConnection conn = new SqlConnection(connstr))
                 {
                     using (SqlCommand cmd = new SqlCommand(sql, conn))
                     {
                         //根據傳來的參數。決定是sql語句還是存儲過程
                         cmd.CommandType = CommandType.StoredProcedure;
                         //添加參數
                         cmd.Parameters.AddRange(paras);
                         conn.Open();
                         using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                         {
                             sda.Fill(ds);
                         }
                     }
                 }
                 return ds;
             }
             /// <summary>
             /// 可以執行sql語句或存儲過程
             /// </summary>
             /// <param name="text"></param>
             /// <param name="ct"></param>
             /// <param name="param"></param>
             /// <returns></returns>
             public static DataTable ProcGetTable(string sql, params SqlParameter[] param)
             {
                 DataTable dt = new DataTable();
    
                 using (SqlConnection conn = new SqlConnection(connstr))
                 {
                     using (SqlCommand cmd = new SqlCommand(sql, conn))
                     {
                         //根據傳來的參數。決定是sql語句還是存儲過程
                         
                         cmd.CommandType = CommandType.StoredProcedure;
                         //添加參數
                         cmd.Parameters.AddRange(param);
                         //cmd.Parameters.Add("@name", SqlDbType.NVarChar, 20).Value = param[0];
                         //cmd.Parameters.Add("@pwd", SqlDbType.NVarChar, 20).Value = param[1];
                         conn.Open();
                         using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                         {
                             sda.Fill(dt);
                         }
                     }
                 }
                 return dt;
             }
            
             /// <summary>
             /// 實現分頁功能
             /// </summary>
             /// <param name="sql">sql語句</param>
             /// <param name="paras">參數數組(顯示index頁和每頁顯示條數size)</param>
             /// <returns>查詢結果</returns>
             public static DataTable GetParaTable(string sql, params SqlParameter[] paras)
             {
                 DataSet ds = new DataSet();
                 using (SqlConnection conn = new SqlConnection(connstr))
                 {
                     using (SqlDataAdapter da = new SqlDataAdapter(sql, conn))
                     {
                         if (paras != null)
                         {
                             da.SelectCommand.Parameters.AddRange(paras);
                         }
                         da.SelectCommand.CommandType = CommandType.StoredProcedure;
                         da.Fill(ds);
                     }
                 }
                 return ds.Tables[0];
             }
        }
    }
    View Code

     

  • 如何選擇文本入庫?
  • 注:通過操作文件,瀏覽文件選擇目標文件,確定后通過流寫入文本框中,另外對目標流文件進行正則表達式處理,自動篩選出需要數據
            //選擇入庫文本
            private void bnt_Click(object sender, RoutedEventArgs e)
            {
                txtcontent.Text = "";
                openData1();
            }
            //入庫文本操作
            public void openData1()
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Title = "打開(Open)";
                ofd.FileName = "";
                //為了獲取特定的系統文件夾,可以使用System.Environment類的靜態方法GetFolderPath()。
                //該方法接受一個Environment.SpecialFolder枚舉,其中可以定義要返回路徑的哪個系統目錄
                ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                ofd.Filter = "文本文件(*.txt)|*.txt";
                ofd.ValidateNames = true;     //文件有效性驗證ValidateNames,驗證用戶輸入是否是一個有效的Windows文件名
                ofd.CheckFileExists = true;  //驗證路徑有效性
                ofd.CheckPathExists = true; //驗證文件有效性
                try
                {
                    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        StreamReader sr = new StreamReader(ofd.FileName, System.Text.Encoding.Default);
                        txtcontent.Text += sr.ReadToEnd();
                        sr.Close();
                        //指定截取書名
                        string str_start = @"書名:(?<info>\w[^。|,^.|^,|^:|^:]+)";//可剔除后邊的中英文逗號,句號等
                        Regex MyRegex = new Regex(str_start, RegexOptions.Multiline);
                        string a = txtcontent.Text;
                        Match MyMatch = MyRegex.Match(a);
                        txttitle.Text=txtdocname.Text = MyMatch.Groups["info"].Value.ToString();
                        //指定截取作者
                        string str_start1 = @"作者:(?<info>\w[^。|,^.|^,|^:|^:]+)";//可剔除后邊的中英文逗號,句號等
                        Regex MyRegex1 = new Regex(str_start1, RegexOptions.Multiline);
                        string b = txtcontent.Text;
                        Match MyMatch1 = MyRegex1.Match(b);
                        txtauthor.Text = MyMatch1.Groups["info"].Value.ToString();
                        //指定截取朝代
                        string str_start2 = @"朝代:(?<info>\w[^。|,^.|^,|^:|^:]+)";//可剔除后邊的中英文逗號,句號等
                        Regex MyRegex2 = new Regex(str_start2, RegexOptions.Multiline);
                        string c = txtcontent.Text;
                        Match MyMatch2 = MyRegex2.Match(c);
                        txtyears.Text = MyMatch2.Groups["info"].Value.ToString();
                    }
                }
                catch (Exception)
                {
                    System.Windows.Forms.MessageBox.Show("讀取文件失敗,請檢查文件格式!");
                }
            }
    View Code

     

  • 如何截取指定文本中的字段?
  •  注:
                        StreamReader sr = new StreamReader(ofd.FileName, System.Text.Encoding.Default);
                        txtcontent.Text += sr.ReadToEnd();
                        sr.Close();
                        //指定截取書名
                        string str_start = @"書名:(?<info>\w[^。|,^.|^,|^:|^:]+)";//可剔除后邊的中英文逗號,句號等
                        Regex MyRegex = new Regex(str_start, RegexOptions.Multiline);
                        string a = txtcontent.Text;
                        Match MyMatch = MyRegex.Match(a);
                        txttitle.Text=txtdocname.Text = MyMatch.Groups["info"].Value.ToString();
                        //指定截取作者
                        string str_start1 = @"作者:(?<info>\w[^。|,^.|^,|^:|^:]+)";//可剔除后邊的中英文逗號,句號等
                        Regex MyRegex1 = new Regex(str_start1, RegexOptions.Multiline);
                        string b = txtcontent.Text;
                        Match MyMatch1 = MyRegex1.Match(b);
                        txtauthor.Text = MyMatch1.Groups["info"].Value.ToString();
                        //指定截取朝代
                        string str_start2 = @"朝代:(?<info>\w[^。|,^.|^,|^:|^:]+)";//可剔除后邊的中英文逗號,句號等
                        Regex MyRegex2 = new Regex(str_start2, RegexOptions.Multiline);
                        string c = txtcontent.Text;
                        Match MyMatch2 = MyRegex2.Match(c);
                        txtyears.Text = MyMatch2.Groups["info"].Value.ToString();
    View Code

     

  • 如何實現批量刪除?
  •  注:利用CheckBox綁定主鍵,操作其遍歷是否被選中,然后通過刪除按鈕進行批量刪除。
           //批量刪除
            List<int> selectFID = new List<int>();  
    
            private void CheckBox_Click(object sender, RoutedEventArgs e)
            {
                System.Windows.Controls.CheckBox dg = sender as System.Windows.Controls.CheckBox;
                int FID = int.Parse(dg.Tag.ToString());   //獲取該行的FID   
                var bl = dg.IsChecked;
                if (bl == true)
                {
                    selectFID.Add(FID);         //如果選中就保存FID   
                }
                else
                {
                    selectFID.Remove(FID);  //如果選中取消就刪除里面的FID   
                }  
               
            }
    
            private void btnDelete_Click(object sender, RoutedEventArgs e)
            {
                foreach (int FID in selectFID)
                {
                    string sql = "delete  T_TCM_THESIS where id=" + FID;
                    int i = SQLHelper.OrlExecuteQuery(sql);
                    if (i > 0)
                    {
                        System.Windows.Forms.MessageBox.Show("success!!!");
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("Erroy!!!");
                    }
                    InitData();
                }  
            }
    View Code

     


 【篇末】:程序中使用oracle數據庫的設計,序列創建,觸發器創建,對目標文件處理,正則表達式運用,wpf分頁,以及DataGrid數據綁定,批量刪除,模版使用等技術,整合完成文件入庫操作。后面對此功能所用核心知識點做以梳理總結。下面最后環節,就是對整個項目測試和頁面最終修訂,然后對審核頁面設計和性能提升。最后會附近本項目完整源碼。

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM