c# vs2010 excel upload oracle data

The excel data table is uploaded to the oracle database. The process is as follows:

1. Open the local excel file

2. Use OleDb to connect the excel file

3. In the future, the data of excel will be read into the dataset

4. Insert the data in the dataset into the corresponding table in oracle

The following screenshots illustrate:


Create project files. very easy. It is to create a normal winform project.

To access oracle, add a reference to System.Data.OracleClient;

vs2010 defaults to .net framework 4.0 client profile. System.Data.OracleClient is not visible when adding references;

Right-click on the project file. Select Properties. A dialog box such as the following will pop up:


Select .net framework 4 in the target framework drop-down box. In this way, when the reference is added, the System.Data.OracleClient can be seen on the .net tab .

Below is all the code

using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Data.OracleClient;


namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "1(*.xlsx)|*.xlsx";
            openFileDialog1.ShowDialog();//打開對話方塊
            this.textBox1.Text = openFileDialog1.FileName;//得到檔=路徑+名稱
        }


        private void button2_Click(object sender, EventArgs e)
        {
            try
            {


                DataSet ds = ImportExcel(this.textBox1.Text);//Put the object of excel into ds first
                if (ds != null)
                {
                    if (ds.Tables [0].Rows.Count > 0)//If there is a value in ds, perform the following operations
                    {
                        if (ExportInfo(ds))
                        {
                            MessageBox.Show("Import database successfully!");
                        }
                        else
                        {
                            MessageBox. Show("Failed to import database!");
                        }
                    }


                }
            }
            catch
            {


                MessageBox.Show("Failed to import database, please check whether the import file is filled in correctly!");
            }
        }


        public static DataSet ImportExcel(string file)
        {
            FileInfo fileInfo = new FileInfo(file);
            if (!fileInfo .Exists) return null; string strConn = @"Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + file + ";Extended Properties='Excel 12.0; HDR=yes; IMEX=2'";

           // 此处用的是excel2010,假设为其它excel版本号。请选择对应的连接驱动和字符串
            OleDbConnection objConn = new OleDbConnection(strConn);
            DataSet dsExcel = new DataSet();
            try
            {
                objConn.Open();
                string strSql = "select * from [Sheet1$]";
                OleDbDataAdapter odbcExcelDataAdapter = new OleDbDataAdapter(strSql, objConn);
                odbcExcelDataAdapter.Fill(dsExcel); return dsExcel;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static bool ExportInfo(DataSet ds)
        {
            if (ds != null)
            {
                if (ds.Tables[0].Rows.Count > 0)//假设ds中是有值的話 執行以下的操作
                {
                    return Do(ds);//執行成功
                }
            }
            return false;//執行失敗
        }
        public static bool Do(DataSet ds)
        {
            OracleConnection conNorthwind = new OracleConnection("Data Source=tiptop;User Id=iteqdg;Password=iteqdg;Integrated Security=no;");//連結字串
            OracleCommand commandNorthwind = new OracleCommand();
            try
            {
                conNorthwind.Open();//打開資料庫連結
                OracleTransaction tranNorthwind = conNorthwind.BeginTransaction();//开始事務
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow dr = ds.Tables[0].Rows[i];
                    OracleParameter[] parameters = null;//為了得到插入資料庫的参數 定義参數物件 為空
                    string sql = GetSqlString(dr, out parameters);//執行sql -->用out關鍵字得到参數 賦到parameters物件上
                    //插入資料庫中
                    PrepareCommand(commandNorthwind, conNorthwind, tranNorthwind, sql, parameters);
                    commandNorthwind.ExecuteNonQuery();//執行操作
                }
                commandNorthwind.Transaction.Commit();//提交事務
                conNorthwind.Close();//關閉資料庫連結資源
                return true;
            }
            catch//假设有異常 不一定要捕捉異常 但要rollback事務
            {
                if (commandNorthwind.Transaction != null && conNorthwind != null)
                {
                    commandNorthwind.Transaction.Rollback();//rollback事務
                    conNorthwind.Close();//關閉資料庫連結
                }
                return false;
            }
        }
        /// <summary>
        /// 每一行資訊插入資料庫中
        /// </summary>
        /// <param name="dr">要插入的這一行ds-datarow對象</param>
        /// <returns>sql語句和用out關鍵字的参數陣列物件</returns>
        public static string GetSqlString(DataRow dr, out OracleParameter[] parameters)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("INSERT INTO TEXT VALUES(:ID,:NAME)");
            parameters = new OracleParameter[] { new OracleParameter(":ID", Convert.ToString(dr[0])), new OracleParameter(":NAME", Convert.ToString(dr[1])) };
            return sb.ToString();//將sqlreturn出去
        }
        private static void PrepareCommand(OracleCommand cmd, OracleConnection conn, OracleTransaction trans, string cmdText, OracleParameter[] cmdParms)
        {
            PrepareCommand(cmd, conn, trans, cmdText, CommandType.Text, cmdParms);
        }
        //参數設定  此方法被重載 
        private static void PrepareCommand(OracleCommand cmd, OracleConnection conn, OracleTransaction trans, string cmdText, CommandType cmdType, OracleParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
            {
                cmd.Transaction = trans;
            }
            cmd.CommandType = cmdType;  // CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (OracleParameter parameter in cmdParms)
                {
                    if (parameter != null)
                    {
                        if (parameter.Value == null)
                        {
                            parameter.Value = DBNull.Value;
                        }
                        cmd.Parameters.Add(parameter);
                    }
                }
            }
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324686538&siteId=291194637