导入Excel数据到数据库

来源:互联网 发布:趋势图指标源码 编辑:程序博客网 时间:2024/05/17 22:36

Oracle下导入Excel数据


代码如下:

using System.Data;
using System.Data.OleDb;
using System.Data.OracleClient;

/// <summary>
/// 根据路径得到excel文件数据
/// </summary>
/// <param name="ProvStr"></param>
/// <param name="SqlStr"></param>
/// <returns></returns>

public DataTablegetExcelData(string FilePath, string sheetName)
{
            string connectStr = string.Format(" Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = {0};Extended Properties='Excel 8.0;HDR=YES;IMEX=1'", FilePath);//Extended Properties='Excel 8.0;HDR=YES;IMEX=1'
            string SqlStr = string.Format("select *  from [{0}$]", sheetName);

            DataSet ds = new DataSet();

            IDbConnection conn = null;
            IDbCommand cmd = null;
            IDbDataAdapter ada = null;
            conn = new OleDbConnection(connectStr);
            cmd = conn.CreateCommand();
            ada = new OleDbDataAdapter();

            try
            {
                conn.Open();
                cmd.CommandText = SqlStr;
                ada.SelectCommand = cmd;
                ada.Fill(ds);
            }
            catch (Exceptionex)
            {
                throw ex;
            }
            finally
            {
                if (conn.State == System.Data.ConnectionState.Open)
                {
                    conn.Close();
                }
            }
            if (ds.Tables.Count > 0)
            {
                return ds.Tables[0];
            }
            else
            {
                return null;
            }
}



/// <summary>
/// 从Excel读取数据
/// </summary>
/// <param name="filePath">路径</param>
/// <returns>DataSet</returns>

public DataSet ImportFromExcel(string filePath)
{
DataSet ds = new DataSet();
string connString = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
DataTable table = OleDbHelper.GetExcelTables(connString);
if(table == null || table.Rows.Count <= 0)
{
return null;
}

foreach(DataRow dr in table.Rows)
{
string cmdText = "select * from [" + dr["TABLE_NAME"].ToString() + "]";
DataTable dt = OleDbHelper.FillDataTable(connString, cmdText);
dt.TableName = dr["TABLE_NAME"].ToString();
ds.Tables.Add(dt);
}

return ds;
}


原创粉丝点击