將Excel資料匯入資料庫

來源:互聯網
上載者:User

標籤:style   blog   http   ar   io   color   os   sp   for   

Excel如下,這頁工作表名叫“線路”

資料庫表如下

 

 

  1 using System;  2 using System.Collections.Generic;  3 using System.Linq;  4 using System.Web;  5 using System.Data;  6 using System.Data.OleDb;  7 using System.Configuration;  8 using System.Data.SqlClient;  9  10 namespace insertData 11 { 12     class FileSvr 13     { 14         /// <summary> 15         /// 擷取DataRow的真實長度 16         /// </summary> 17         /// <param name="dr">DataRow</param> 18         /// <returns>真實長度</returns> 19         public int getRowLen(DataRow dr) 20         { 21             int i = 0; 22             for (; i < dr.ItemArray.Length; i++) 23                 if (dr[i].ToString().Trim() == "") break; 24             return i; 25         } 26         /// <summary> 27         /// //Excel指定的工作表資料匯入Datable 28         /// </summary> 29         /// <param name="fileUrl">Excel路徑</param> 30         /// <param name="sheetName">工作表名</param> 31         /// <returns></returns> 32         public DataTable getExcelDatatable(string fileUrl, string sheetName)//Excel指定的工作表資料匯入Datable 33         { 34             //支援.xls和.xlsx,即包括office2010等版本的   HDR=Yes代表第一行是標題,不是資料; 35             const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties=‘Excel 12.0; HDR=Yes; IMEX=1‘"; 36  37             DataTable dt = null; 38             //建立串連 39             OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl)); 40             try 41             { 42                 //開啟串連 43                 if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed) 44                 { 45                     conn.Open(); 46                 } 47  48                 //查詢sheet中的資料 49                 string strSql = "select * from [" + sheetName + "$]"; 50                 OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn); 51                 DataSet ds = new DataSet(); 52                 da.Fill(ds); 53                 dt = ds.Tables[0]; 54                 return dt; 55             } 56             catch (Exception exc) 57             { 58                 throw exc; 59             } 60             finally 61             { 62                 conn.Close(); 63                 conn.Dispose(); 64             } 65         } 66 public void InsertRoute(DataTable dt, string strConnection,int dir)//從DataTable匯入資料到資料庫 67         { 68             int retVal = 0; 69             int count0 = 0; 70             int count = 0; 71             int routeNo; 72             SqlConnection conn = new SqlConnection(strConnection); 73             conn.Open(); 74             string strSql; 75             SqlCommand sqlCmd = new SqlCommand(); 76             sqlCmd.Connection = conn; 77             sqlCmd.Parameters.Add("@編號", System.Data.SqlDbType.Int, 4); 78             sqlCmd.Parameters.Add("@線路號", System.Data.SqlDbType.Int, 4); 79             sqlCmd.Parameters.Add("@行向", System.Data.SqlDbType.Int, 4); 80             sqlCmd.Parameters.Add("@線路名稱", System.Data.SqlDbType.NVarChar, 50); 81             sqlCmd.Parameters.Add("@始發網站", System.Data.SqlDbType.NVarChar, 50); 82             sqlCmd.Parameters.Add("@開往方向", System.Data.SqlDbType.NVarChar, 50); 83             sqlCmd.Parameters.Add("@更新時間", System.Data.SqlDbType.DateTime, 4); 84             foreach (DataRow dr in dt.Rows)//遍曆行資料 85             { 86                 strSql= "update 線路 set 線路號[email protected]線路號, 行向[email protected]行向, 線路名稱[email protected]線路名稱, 始發網站[email protected]始發網站, 開往方向[email protected]開往方向,更新時間[email protected]更新時間 where 編號[email protected]編號"; 87                 sqlCmd.CommandText = strSql; 88                 routeNo =Convert.ToInt32(dr[0].ToString().Trim()); 89                 sqlCmd.Parameters["@編號"].Value = routeNo+dir*100000; 90                 sqlCmd.Parameters["@線路號"].Value=routeNo; 91                 sqlCmd.Parameters["@行向"].Value=dir; 92                 sqlCmd.Parameters["@線路名稱"].Value=routeNo+"路"; 93                 sqlCmd.Parameters["@始發網站"].Value=dr[1].ToString(); 94                 sqlCmd.Parameters["@開往方向"].Value=dr[getRowLen(dr)-1].ToString(); 95                 sqlCmd.Parameters["@更新時間"].Value = DateTime.Now; 96                 retVal = sqlCmd.ExecuteNonQuery(); 97                 if (retVal == 0) 98                 { 99                     strSql = @"insert into 線路( 編號, 線路號, 行向, 線路名稱, 始發網站, 開往方向, 更新時間) values(@編號,@線路號,@行向,@線路名稱,@始發網站,@開往方向,@更新時間)";100                     sqlCmd.CommandText = strSql;101                     retVal = sqlCmd.ExecuteNonQuery();102                     count++;103                     Console.WriteLine("插入線路{0}成功!", routeNo);104                 }105                 else106                 {107                     count0++;108                     Console.WriteLine("更新線路{0}成功!", routeNo);109                 }110             }111             conn.Close();112             Console.WriteLine("插入{0}條、更新{1}條線路",count, count0);113         }114 }
View Code

結果如下

 

將Excel資料匯入資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.