c#中高效的excel导入oracle的方法

来源:互联网 发布:如何设计软件界面 编辑:程序博客网 时间:2024/05/16 05:03

如何高效的将excel导入到oracle?和前两天的SqlBulkCopy 导入到sqlserver对应,oracle也有自身的方法,只是稍微复杂些.
那就是使用oracle的sql*loader功能,而sqlldr只支持类似csv格式的数据,所以要自己把excel转换一下。
实现步骤:
用com组件读取excel-保存为csv格式-处理最后一个字段为null的情况和表头-根据excel结构建表-生成sqlldr的控制文件-用sqlldr命令导入数据
这个性能虽然没有sql的bcp快,但还是相当可观的,在我机器上1万多数据不到4秒,而且导入过程代码比较简单,也同样没有循环拼接sql插入那么难以维护。

这里也提个问题:处理csv文件的表头和最后一个字段为null的情况是否可以优化?除了我代码中的例子,我实在想不出其他办法。

 

view plaincopy to clipboardprint?
  1. using System;   
  2. using System.Data;   
  3. using System.Text;   
  4. using System.Windows.Forms;   
  5. using Microsoft.Office.Interop.Excel;   
  6. using System.Data.OleDb;   
  7. //引用-com-microsoft excel objects 11.0   
  8. namespace WindowsApplication5   
  9. {   
  10.     public partial class Form1 : Form   
  11.     {   
  12.         public Form1()   
  13.         {   
  14.             InitializeComponent();   
  15.         }   
  16.     
  17.         /// <SUMMARY>   
  18.         /// excel导入到oracle   
  19.         /// </SUMMARY>   
  20.         /// <PARAM name="excelFile">文件名</PARAM>   
  21.         /// <PARAM name="sheetName">sheet名</PARAM>   
  22.         /// <PARAM name="sqlplusString">oracle命令sqlplus连接串</PARAM>   
  23.         public void TransferData(string excelFile, string sheetName, string sqlplusString)   
  24.         {   
  25.             string strTempDir = System.IO.Path.GetDirectoryName(excelFile);   
  26.             string strFileName = System.IO.Path.GetFileNameWithoutExtension(excelFile);   
  27.             string strCsvPath = strTempDir +"//"+strFileName + ".csv";   
  28.             string strCtlPath = strTempDir + "//" + strFileName + ".Ctl";   
  29.             string strSqlPath = strTempDir + "//" + strFileName + ".Sql";   
  30.             if (System.IO.File.Exists(strCsvPath))   
  31.                 System.IO.File.Delete(strCsvPath);   
  32.   
  33.   
  34.             //获取excel对象   
  35.             Microsoft.Office.Interop.Excel.Application ObjExcel = new Microsoft.Office.Interop.Excel.Application();   
  36.   
  37.             Microsoft.Office.Interop.Excel.Workbook ObjWorkBook;   
  38.   
  39.             Microsoft.Office.Interop.Excel.Worksheet ObjWorkSheet = null;   
  40.   
  41.             ObjWorkBook = ObjExcel.Workbooks.Open(excelFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);   
  42.   
  43.             foreach (Microsoft.Office.Interop.Excel.Worksheet sheet in ObjWorkBook.Sheets)   
  44.             {   
  45.                 if (sheet.Name.ToLower() == sheetName.ToLower())   
  46.                 {   
  47.                     ObjWorkSheet = sheet;   
  48.                     break;   
  49.                 }   
  50.             }   
  51.             if (ObjWorkSheet == nullthrow new Exception(string.Format("{0} not found!!", sheetName));   
  52.   
  53.   
  54.             //保存为csv临时文件   
  55.             ObjWorkSheet.SaveAs(strCsvPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV, Type.Missing, Type.Missing, falsefalsefalse, Type.Missing, Type.Missing, false);   
  56.             ObjWorkBook.Close(false, Type.Missing, Type.Missing);   
  57.             ObjExcel.Quit();   
  58.   
  59.             //读取csv文件,需要将表头去掉,并且将最后一列为null的字段处理为显示的null,否则oracle不会识别,这个步骤有没有好的替换方法?   
  60.             System.IO.StreamReader reader = new System.IO.StreamReader(strCsvPath,Encoding.GetEncoding("gb2312"));   
  61.             string strAll = reader.ReadToEnd();   
  62.             reader.Close();   
  63.             string strData = strAll.Substring(strAll.IndexOf("/r/n") + 2).Replace(",/r/n",",Null");   
  64.   
  65.             byte[] bytes = System.Text.Encoding.Default.GetBytes(strData);   
  66.             System.IO.Stream ms = System.IO.File.Create(strCsvPath);   
  67.             ms.Write(bytes, 0, bytes.Length);   
  68.             ms.Close();   
  69.   
  70.   
  71.             //获取excel表结构   
  72.             string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFile + ";" + "Extended Properties=Excel 8.0;";   
  73.             OleDbConnection conn = new OleDbConnection(strConn);   
  74.             conn.Open();   
  75.             System.Data.DataTable table = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Columns,   
  76.                 new object[] { nullnull, sheetName+"$"null });   
  77.   
  78.   
  79.             //生成sqlldr用到的控制文件,文件结构参考sql*loader功能,本示例已逗号分隔csv,数据带逗号的用引号括起来。      
  80.             string strControl =  "load data/r/ninfile &apos;{0}&apos; /r/nappend into table {1}/r/n"+       
  81.                   "FIELDS TERMINATED BY &apos;,&apos; OPTIONALLY ENCLOSED BY &apos;/"&apos;/r/n(";     
  82.             strControl = string.Format(strControl, strCsvPath,sheetName);   
  83.             foreach (System.Data.DataRow drowColumns in table.Select("1=1""Ordinal_Position"))   
  84.             {   
  85.                 strControl += drowColumns["Column_Name"].ToString() + ",";   
  86.             }   
  87.   
  88.             strControl = strControl.Substring(0, strControl.Length - 1) + ")";   
  89.             bytes=System.Text.Encoding.Default.GetBytes(strControl);   
  90.             ms= System.IO.File.Create(strCtlPath);   
  91.   
  92.             ms.Write(bytes, 0, bytes.Length);   
  93.             ms.Close();   
  94.   
  95.             //生成初始化oracle表结构的文件   
  96.             string strSql = @"drop table {0};               
  97.                   create table {0}    
  98.                   (";   
  99.             strSql = string.Format(strSql, sheetName);   
  100.             foreach (System.Data.DataRow drowColumns in table.Select("1=1""Ordinal_Position"))   
  101.             {   
  102.                 strSql += drowColumns["Column_Name"].ToString() + " varchar2(255),";   
  103.             }   
  104.             strSql = strSql.Substring(0, strSql.Length - 1) + ");/r/nexit;";   
  105.             bytes = System.Text.Encoding.Default.GetBytes(strSql);   
  106.             ms = System.IO.File.Create(strSqlPath);   
  107.   
  108.             ms.Write(bytes, 0, bytes.Length);   
  109.             ms.Close();   
  110.   
  111.   
  112.             //运行sqlplus,初始化表   
  113.             System.Diagnostics.Process p = new System.Diagnostics.Process();   
  114.             p.StartInfo = new System.Diagnostics.ProcessStartInfo();   
  115.             p.StartInfo.FileName = "sqlplus";   
  116.             p.StartInfo.Arguments = string.Format("{0} @{1}", sqlplusString, strSqlPath);   
  117.             p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;   
  118.             p.StartInfo.UseShellExecute = false;   
  119.             p.StartInfo.CreateNoWindow = true;   
  120.             p.Start();   
  121.             p.WaitForExit();   
  122.   
  123.             //运行sqlldr,导入数据   
  124.             p = new System.Diagnostics.Process();   
  125.             p.StartInfo = new System.Diagnostics.ProcessStartInfo();   
  126.             p.StartInfo.FileName = "sqlldr";   
  127.             p.StartInfo.Arguments = string.Format("{0} {1}", sqlplusString, strCtlPath);   
  128.             p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;   
  129.             p.StartInfo.RedirectStandardOutput = true;   
  130.             p.StartInfo.UseShellExecute = false;   
  131.             p.StartInfo.CreateNoWindow = true;   
  132.             p.Start();   
  133.             System.IO.StreamReader r = p.StandardOutput;//截取输出流   
  134.             string line = r.ReadLine();//每次读取一行   
  135.             textBox3.Text += line + "/r/n";   
  136.             while (!r.EndOfStream)   
  137.             {   
  138.                 line = r.ReadLine();   
  139.                 textBox3.Text += line + "/r/n";   
  140.                 textBox3.Update();   
  141.             }   
  142.             p.WaitForExit();   
  143.   
  144.             //可以自行解决掉临时文件csv,ctl和sql,代码略去   
  145.         }   
  146.   
  147.         private void button1_Click(object sender, EventArgs e)   
  148.         {   
  149.             TransferData(@"D:/test.xls""Sheet1""username/password@servicename");   
  150.         }   
  151.            
  152.     }   
  153. }
 
原创粉丝点击