using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Oracle.ManagedDataAccess.Client;
namespace excel表匯入oracle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
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=1'";
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;
}
}
/// <summary>
/// 這是將ds物件匯入資料庫的方法
/// 代云超
/// </summary>
/// <returns>執行是否成功 如: 成功=true 失敗=false</returns>
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=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=https://bbs.csdn.net/topics/(SERVICE_NAME=orcl)));Persist Security Info=True;User ID=system;Password=orcl;");//鏈接字串
OracleCommand commandNorthwind = new OracleCommand();
try
{
conNorthwind.Open();//打開資料庫鏈接
OracleTransaction tranNorthwind = conNorthwind.BeginTransaction();//開始事務
Console.WriteLine("行數"+ds.Tables[0].Rows.Count);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
DataRow dr = ds.Tables[0].Rows[i];