读取Excel内容,导入数据库多张表!

客户要求用Excel记录联系人资料,并导入数据库,找了个第3方Wizard控件做了个小功能。
Excel每一个sheet为一个企业名,为了避免麻烦,一次性导入所有联系人。
 同一企业下的相同姓名,相同手机号的为同一个联系人,就不导入。
Excel表中,有些字段不在同一张表:“部门”、“职务”。判断部门和职务是否存在,若不存在添加到部门和职务表,返回ID。
几次测试,取手机号等字段出错,原来要把Excel单元格格式设为文本。
/*         Author : Magicam 
 *         Date   : 1 August 2007
 *         e-mail : wx_magicam@sina.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;
            }

        }

    }

}
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是Java导入Excel表到数据库张表中的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Iterator; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook;import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelImporter { public static void main(String[] args) { String excelFilePath = "path/to/excel/file.xlsx"; try { FileInputStream inputStream = new FileInputStream(new File(excelFilePath)); Workbook workbook = new XSSFWorkbook(inputStream); Iterator<Sheet> sheetIterator = workbook.iterator(); while (sheetIterator.hasNext()) { Sheet sheet = sheetIterator.next(); String tableName = sheet.getSheetName(); Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); // 获取数据库连接 Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "username", "password"); // 构建插入语句 StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO ").append(tableName).append(" VALUES ("); for (int i = 0; i < row.getLastCellNum(); i++) { sql.append("?,"); } sql.deleteCharAt(sql.length() - 1); sql.append(")"); // 创建预编译语句 PreparedStatement statement = connection.prepareStatement(sql.toString()); int cellIndex = 0; while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); statement.setString(cellIndex + 1, cell.getStringCellValue()); cellIndex++; } // 执行插入语句 statement.executeUpdate(); // 关闭连接和语句 statement.close(); connection.close(); } } workbook.close(); inputStream.close(); System.out.println("Excel导入数据库成功!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 请注意,上述代码中的数据库连接信息需要根据实际情况进行修改。此外,还需要添加Apache POI和MySQL驱动的依赖。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值