zoukankan      html  css  js  c++  java
  • 读取Excel内容,导入数据库多张表!

    客户要求用Excel记录联系人资料,并导入数据库,找了个第3方Wizard控件做了个小功能。
    Excel每一个sheet为一个企业名,为了避免麻烦,一次性导入所有联系人。
     同一企业下的相同姓名,相同手机号的为同一个联系人,就不导入。
    Excel表中,有些字段不在同一张表:“部门”、“职务”。判断部门和职务是否存在,若不存在添加到部门和职务表,返回ID。
    几次测试,取手机号等字段出错,原来要把Excel单元格格式设为文本。
    /* 
                  Author:Magicam
     *         Date: 1 August 2007
                  Email:wx_magicam@qq.com
     * 
    */
            
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using System.Data.OleDb;
    using CristiPotlog.Controls;//引用第3方向导式控件
    using System.Configuration;

    namespace Excel
    {
        
    public partial class ExcelForm : Form
        
    {
            
    public ExcelForm()
            
    {
                InitializeComponent();
            }


            
    public static readonly string ConnectionString = ConfigurationManager.ConnectionStrings[ "DataConnectionString" ].ConnectionString;

            
    /// <summary>
            
    /// 完成按钮
            
    /// </summary>
            
    /// <param name="sender"></param>
            
    /// <param name="e"></param>

            private void wizard1_Finish( object sender, EventArgs e )
            
    {
                MessageBox.Show( 
    "导入成功!"this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information );
            }


            
    private void wizard1_Cancel( object sender, CancelEventArgs e )
            
    {
                
    bool isTaskRunning = this.timer1.Enabled;
                
    this.timer1.Enabled = false;

                
    if ( MessageBox.Show( "确定退出吗?"this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question ) != DialogResult.Yes )
                
    {
                    e.Cancel 
    = true;
                    
    this.timer1.Enabled = isTaskRunning;
                }

            }


            
    /// <summary>
            
    /// time控件
            
    /// </summary>
            
    /// <param name="sender"></param>
            
    /// <param name="e"></param>

            private void timer1_Tick( object sender, EventArgs e )
            
    {
                
    if ( this.progressBar1.Value == this.progressBar1.Maximum )
                
    {
                    
    this.timer1.Enabled = false;
                    
    this.wizard1.Next();
                }

                
    else
                
    {
                    
    this.progressBar1.PerformStep();
                }

            }


            
    /// <summary>
            
    /// 选择Excel按钮
            
    /// </summary>
            
    /// <param name="sender"></param>
            
    /// <param name="e"></param>

            private void btnChooseExcel_Click( object sender, EventArgs e )
            
    {
                OpenFileDialog openFileDialog 
    = new OpenFileDialog();
                openFileDialog.Filter 
    = "Microsoft Excel 文件(*.xls)|*.xls";
                openFileDialog.Title 
    = "选择Excel文件";

                
    if ( DialogResult.Cancel == openFileDialog.ShowDialog())
                
    {
                    
    return;
                }


                
    string ExcelPath = openFileDialog.FileName;
                txtExcelPath.Text 
    = ExcelPath;

                
    string ConnectionExcel = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + ExcelPath + ";" + "Extended Properties=Excel 8.0;";

                OleDbConnection conn 
    = new OleDbConnection( ConnectionExcel );
                conn.Open();
                System.Data.DataTable schemaTable 
    = conn.GetOleDbSchemaTable( System.Data.OleDb.OleDbSchemaGuid.Tables, null );

                dataGridView1.Rows.Clear();
                dataGridView1.Columns.Clear();

                
    //定义dataGridView第一列
                dataGridView1.RowHeadersVisible = false;
                DataGridViewTextBoxColumn textColumn 
    = new DataGridViewTextBoxColumn();
                textColumn.HeaderText 
    = "工作表";
                dataGridView1.Columns.Insert( 
    0, textColumn );
                
    //定义dataGridView第二列
                DataGridViewComboBoxColumn comboColumn = new DataGridViewComboBoxColumn();
                comboColumn.HeaderText 
    = "选择企业";
                comboColumn.AutoComplete 
    = true;
                dataGridView1.Columns.Insert( 
    1, comboColumn );

                SqlConnection con 
    = new SqlConnection( ConnectionString );
                con.Open();

                
    forint i = 0; i < schemaTable.Rows.Count; i++ )
                
    {
                    
    //取出Excel工作表名导入dataGridView第一列
                    string tableName = schemaTable.Rows[ i ][ 2 ].ToString().Trim( new char[] '$''\'' } );
                    dataGridView1.Rows.Add();
                    dataGridView1.Rows[ i ].Cells[ 
    0 ].Value = tableName;

                    OnInitComboBox( i );
                }
              
            }


            
    private void OnInitComboBox( int row )
            
    {
                
    //第二列根据第一列做模糊查询,供用户选择企业名
                SqlConnection con = new SqlConnection( ConnectionString );
                con.Open();

                SqlDataAdapter sda 
    = new SqlDataAdapter();
                DataSet ds 
    = new DataSet();

                
    string name = dataGridView1.Rows[ row ].Cells[ 0 ].Value.ToString();
                
    string str = "select id, name from enterprise where name like '%" + name + "%'";

                sda.SelectCommand 
    = new SqlCommand( str, con );
                sda.Fill( ds, 
    "enterprise" );

                (( DataGridViewComboBoxCell )( dataGridView1.Rows[ row ].Cells[ 
    1 ] )).DataSource    = ds.Tables[ 0 ].DefaultView;
                (( DataGridViewComboBoxCell )( dataGridView1.Rows[ row ].Cells[ 
    1 ] )).ValueMember   = "id";
                (( DataGridViewComboBoxCell )( dataGridView1.Rows[ row ].Cells[ 
    1 ] )).DisplayMember = "name";
            }


            
    private void wizard1_BeforeSwitchPages( object sender, Wizard.BeforeSwitchPagesEventArgs e )
            
    {
                WizardPage oldPage 
    = this.wizard1.Pages[ e.OldIndex ];

                
    if ( oldPage == this.ChooseExcelPage && e.NewIndex > e.OldIndex )
                
    {                
                    
    if ( txtExcelPath.Text == "" )
                    
    {                   
                        MessageBox.Show( 
    "请选择一个Excel文件!"this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information );
                        e.Cancel 
    = true;
                    }

                }

                
    else if( oldPage == this.ChooseEnterprisePage && e.NewIndex > e.OldIndex )
                
    {
                    SqlConnection con 
    = new SqlConnection( ConnectionString );
                    con.Open();

                    
    forint i = 0; i<dataGridView1.Rows.Count; i++ )
                    
    {
                        
    if( dataGridView1.Rows[ i ].Cells[ 1 ].Value == null )
                        
    {
                            MessageBox.Show( 
    "请选择企业!",  this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information );                        
                            e.Cancel 
    = true;
                        }
                        
                    }

                }

                
    else if( oldPage == this.ProgressPage && e.NewIndex > e.OldIndex )
                
    {
                    
    //导入数据库 
                    forint i = 0; i<dataGridView1.Rows.Count; i++ )
                    
    {
                        
    //读取Excel内容到table
                        DataSet DataSet = ReadExcelToTable( i );                                 

                        
    forint j = 0; j<DataSet.Tables[ 0 ].Rows.Count; j++ )
                        
    {
                            SqlConnection con 
    = new SqlConnection( ConnectionString );
                            con.Open();   
                            SqlTransaction transaction;
                            transaction 
    = con.BeginTransaction();
                            
    try
                            
    {
                                
    //判断联系人是否重复,若重复跳出循环,不添加
                                string LinkmanName = DataSet.Tables[ 0 ].Rows[ j ].ItemArray[ 0 ].ToString();
                                
    string LinkmanMobile = DataSet.Tables[ 0 ].Rows[ j ].ItemArray[ 3 ].ToString();
                                SqlCommand selectLinkmanName 
    = new SqlCommand();
                                selectLinkmanName.Connection 
    = con;
                                selectLinkmanName.CommandText 
    = "select count( * ) from linkman where enterpriseid='" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "'and name='" + LinkmanName + "' and mobile='" + LinkmanMobile + "'";
                                selectLinkmanName.Transaction 
    = transaction;
                                
    int LinkmanCount = Convert.ToInt32( selectLinkmanName.ExecuteScalar());

                                
    if( LinkmanCount > 0 )
                                
    {
                                    
    continue;                               
                                }
                

                                
    //判断是否存在该部门,不存在添加                   
                                int departmentID = ExistDepartment( con, DataSet, j, transaction );

                                
    //判断是否存在该职务,不存在添加
                                int dutyID = ExistDuty( con, DataSet, j, transaction );

                                
    //导入数据库
                                InsertTOSql( con, i, DataSet, j, departmentID, dutyID, transaction );
                            }

                            
    catch( Exception e1 )
                            
    {
                                transaction.Rollback();        
                            }

                            
    finally
                            
    {
                                transaction.Commit();
                                con.Close();
                            }

                        }

                    }
     
                }

            }


            
    private void InsertTOSql( SqlConnection con, int i, DataSet DataSet, int j, int departmentID, int dutyID, SqlTransaction transaction )
            
    {
                SqlCommand insertToSql 
    = new SqlCommand();
                insertToSql.Connection 
    = con;
                insertToSql.CommandText 
    = @"insert into linkman( enterpriseID, name, departmentID, dutyID, mobile, phone, email, fax, IsLinkman )
                                          values( 
    " + dataGridView1.Rows[ i ].Cells[ 1 ].Value.ToString() + ", '" + DataSet.Tables[ 0 ].Rows[ j ].ItemArray[ 0 ].ToString() + "', " + departmentID + ""
                              
    + dutyID + ", '" + DataSet.Tables[ 0 ].Rows[ j ].ItemArray[ 3 ].ToString() + "', '" + DataSet.Tables[ 0 ].Rows[ j ].ItemArray[ 4 ].ToString() + "', '" +
                              DataSet.Tables[ 
    0 ].Rows[ j ].ItemArray[ 5 ].ToString() + "', '" + DataSet.Tables[ 0 ].Rows[ j ].ItemArray[ 6 ].ToString() + "', 1 )"
                insertToSql.Transaction 
    = transaction;
                insertToSql.ExecuteNonQuery();            
            }


            
    private static int ExistDuty( SqlConnection con, DataSet DataSet, int j, SqlTransaction transaction )
            
    {
                SqlCommand selectDuty 
    = new SqlCommand();
                selectDuty.Connection 
    = con;
                selectDuty.CommandText 
    = "select id from duty where name ='" + DataSet.Tables[ 0 ].Rows[ j ].ItemArray[ 2 ].ToString() + "'";
                selectDuty.Transaction 
    = transaction;
                
    int dutyID = Convert.ToInt32( selectDuty.ExecuteScalar());
                
    if ( dutyID == 0 )
                
    {
                    SqlCommand insertDuty 
    = new SqlCommand();
                    insertDuty.Connection 
    = con;
                    insertDuty.CommandText 
    = "insert into duty( name ) values( '" + DataSet.Tables[0].Rows[ j ].ItemArray[ 2 ].ToString() + "')";
                    insertDuty.Transaction 
    = transaction;
                    insertDuty.ExecuteNonQuery(); 
                   
                    dutyID 
    = GetID( con, transaction );
                }

                
    return dutyID;
            }


            
    private static int ExistDepartment( SqlConnection con, DataSet DataSet, int j, SqlTransaction transaction )
            
    {
                SqlCommand selectDepartment 
    = new SqlCommand();
                selectDepartment.Connection 
    = con;
                selectDepartment.CommandText 
    = "select id from department where name = '" + DataSet.Tables[ 0 ].Rows[ j ].ItemArray[ 1 ].ToString() + "'";
                selectDepartment.Transaction 
    = transaction;
                
    int departmentID = Convert.ToInt32( selectDepartment.ExecuteScalar());
                
    if ( departmentID == 0 )
                
    {
                    SqlCommand insertDepartment 
    = new SqlCommand();
                    insertDepartment.Connection 
    = con;

                    insertDepartment.CommandText 
    = "insert into department( name ) values( '" + DataSet.Tables[ 0 ].Rows[ j ].ItemArray[ 1 ].ToString() + "' )";
                    insertDepartment.Transaction 
    = transaction;
                    insertDepartment.ExecuteNonQuery();
                   
                    departmentID 
    = GetID( con, transaction );
                }

                
    return departmentID;
            }


            
    private static int GetID( SqlConnection con, SqlTransaction transaction )
            
    {
                
    string sql = "select @@identity";
                SqlCommand command 
    = new SqlCommand( sql, con );
                command.Transaction 
    = transaction;
                
    return Convert.ToInt32( command.ExecuteScalar());
            }


            
    private DataSet ReadExcelToTable( int i )
            
    {
                
    string ConnectionExcel = "Provider=Microsoft.Jet.Oledb.4.0;Data Source='" + txtExcelPath.Text + "';Extended Properties=Excel 8.0";
                OleDbConnection connection 
    = new OleDbConnection( ConnectionExcel );
                OleDbDataAdapter adp 
    = new OleDbDataAdapter( "Select * from  [" + dataGridView1.Rows[ i ].Cells[ 0 ].Value.ToString() + "$]", connection );
                DataSet DataSet 
    = new DataSet();
                adp.Fill( DataSet, 
    "Book1" );
                
    return DataSet;
            }


            
    private void wizard1_AfterSwitchPages( object sender, Wizard.AfterSwitchPagesEventArgs e )
            
    {
                WizardPage newPage 
    = this.wizard1.Pages[ e.NewIndex ];

                
    if( newPage == this.ChooseExcelPage )
                
    {
                    
    this.wizard1.NextEnabled = this.ChooseEnterprisePage.Enabled;
                }

                
    else if( newPage == this.ChooseEnterprisePage )
                
    {
                    
    this.wizard1.NextEnabled = this.ProgressPage.Enabled;
                }

                
    else if( newPage == this.ProgressPage)
                
    {
                    
    this.wizard1.BackEnabled = false;
                    
    this.wizard1.NextEnabled = false;
                    
    this.progressBar1.Value = this.progressBar1.Minimum;
                    
    this.timer1.Enabled = true;
                }

            }

        }

    }



  • 相关阅读:
    Javascript 生成全局唯一标识符 (GUID,UUID)
    nginx 与location语法详解
    nginx的安装与使用
    Linux上python3的安装和使用
    Linux上Redis安装和简单操作
    MySQL + centos +主从复制
    web服务基础
    linux系统基础优化及高级操作命令
    vim编辑
    Linux的基本命令
  • 原文地址:https://www.cnblogs.com/Magicam/p/838290.html
Copyright © 2011-2022 走看看