c# vs2010 excel 上傳oracle資料

來源:互聯網
上載者:User

標籤:

excel 資料表上傳到oracle資料庫,步驟如下:

1、開啟本地excel檔案

2、用OleDb串連excel檔案

3、將來excel的資料讀取到dataset中

4、把dataset 中資料insert到oracle中相應的表中

下面說明:


建立專案檔,很簡單,就是建立普通的winform項目。其中訪問oracle要添加引用System.Data.OracleClient;

vs2010 預設是.net framework 4.0 client profile 。在添加引用時是看不到System.Data.OracleClient;需要在

專案檔上右擊,選擇屬性。會彈出如下對話方塊:


在target framework 下拉框中 選擇.net framework 4。這樣後續添加引用時,才能在.net頁簽看到System.Data.OracleClient;

下面是全部代碼

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);//將excel的對象先放到ds 中
                if (ds != null)
                {
                    if (ds.Tables[0].Rows.Count > 0)//如果ds中是有值的話 執行下面的操作
                    {
                        if (ExportInfo(ds))
                        {
                            MessageBox.Show("導入資料庫成功!");
                        }
                        else
                        {
                            MessageBox.Show("導入資料庫失敗!");
                        }
                    }


                }
            }
            catch
            {


                MessageBox.Show("導入資料庫失敗 請檢查導入檔是否填寫正確!");
            }
        }


        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);
                    }
                }
            }
        }
    }
}

c# vs2010 excel 上傳oracle資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.