淡水求咸

博客园已经停止更新,请移步 http://lovecjh.com/

导航

将Excel中数据导入数据库(一)

  在工作中经常要将Excel中数据导入数据库,这里介绍一种方法。

  假如Excel中的数据如下:

  数据库建表如下:

  其中Id为自增字段:

  Excel中数据导入数据库帮助类如下:

  1 using System;
  2 using System.Data;
  3 using System.Data.OleDb;
  4 using System.Configuration;
  5 using System.Data.SqlClient;
  6 
  7 /*
  8  * 功能:文件操作类(读取、写入)
  9  */ 
 10 namespace ExcelToDataBaseHelper.Service
 11 {
 12     class FileSvr
 13     {
 14         public FileSvr()
 15         {
 16 
 17         }
 18 
 19         /// <summary>
 20         /// Excel数据导入Datable
 21         /// </summary>
 22         /// <param name="fileUrl"></param>
 23         /// <param name="table"></param>
 24         /// <returns></returns>
 25         public System.Data.DataTable GetExcelDatatable(string fileUrl, string table)
 26         {
 27             //office2007之前 仅支持.xls
 28             //const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=1';";
 29             //支持.xls和.xlsx,即包括office2010等版本的   HDR=Yes代表第一行是标题,不是数据;
 30             const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
 31 
 32             System.Data.DataTable dt = null;
 33             //建立连接
 34             OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));
 35             try
 36             {
 37                 //打开连接
 38                 if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
 39                 {
 40                     conn.Open();
 41                 }
 42 
 43 
 44                 System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
 45                 
 46                 //获取Excel的第一个Sheet名称
 47                 string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();
 48 
 49                 //查询sheet中的数据
 50                 string strSql = "select * from [" + sheetName + "]";
 51                 OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);
 52                 DataSet ds = new DataSet();
 53                 da.Fill(ds, table);
 54                 dt = ds.Tables[0];
 55 
 56                 return dt;
 57             }
 58             catch (Exception exc)
 59             {
 60                 throw exc;
 61             }
 62             finally
 63             {
 64                 conn.Close();
 65                 conn.Dispose();
 66             }
 67 
 68         }
 69 
 70         /// <summary>
 71         /// 从System.Data.DataTable导入数据到数据库
 72         /// </summary>
 73         /// <param name="dt"></param>
 74         /// <returns></returns>
 75         public int InsetData(System.Data.DataTable dt)
 76         {
 77             int i = 0;
 78             string lng = "";
 79             string lat = "";
 80             string offsetLNG = "";
 81             string offsetLAT = "";
 82 
 83             foreach (DataRow dr in dt.Rows)
 84             {
 85                 lng = dr["LNG"].ToString().Trim();
 86                 lat = dr["LAT"].ToString().Trim();
 87                 offsetLNG = dr["OFFSET_LNG"].ToString().Trim();
 88                 offsetLAT = dr["OFFSET_LAT"].ToString().Trim(); 
 89 
 90                 //sw = string.IsNullOrEmpty(sw) ? "null" : sw;
 91                 //kr = string.IsNullOrEmpty(kr) ? "null" : kr;
 92 
 93                 string strSql = string.Format("Insert into Google_Offset2 (LNG,LAT,OFFSET_LNG,OFFSET_LAT) Values ('{0}','{1}',{2},{3})", lng, lat, offsetLNG, offsetLAT);
 94 
 95                 String strConnection = ConfigurationSettings.AppSettings["ConnectionStr"].ToString();
 96                 SqlConnection sqlConnection = new SqlConnection(strConnection);
 97                 try
 98                 {
 99                     // SqlConnection sqlConnection = new SqlConnection(strConnection);
100                     sqlConnection.Open();
101                     SqlCommand sqlCmd = new SqlCommand();
102                     sqlCmd.CommandText = strSql;
103                     sqlCmd.Connection = sqlConnection;
104                     SqlDataReader sqlDataReader = sqlCmd.ExecuteReader();
105                     i++;
106                     sqlDataReader.Close();
107 
108 
109                 }
110                 catch (Exception ex)
111                 {
112                     throw ex;
113                 }
114                 finally
115                 {
116 
117                     sqlConnection.Close();
118 
119                 }
120                 
121                 //if (opdb.ExcSQL(strSql))
122                 //    i++;
123             }
124             return i;
125         }
126     }
127 }
查看代码

  调用代码如下:

FileSvr fileSvr = new FileSvr();
System.Data.DataTable dt = fileSvr.GetExcelDatatable("../../excel/1.xlsx", "mapTable");
fileSvr.InsetData(dt);

  运行结果如下:

 

  相关文章:

  (1)将Excel中数据导入数据库(一)

  (2)将Excel中数据导入数据库(二)

  (3)将Excel中数据导入数据库(三)

  

posted on 2013-07-03 12:56  深圳彦祖  阅读(5012)  评论(0编辑  收藏  举报