将Excel文件数据导入到SqlServer数据库的三种方案

时间:2021-07-22 11:46:20

方案一: 通过OleDB方式获取Excel文件的数据,然后通过DataSet中转到SQL Server,这种方法的优点是非常的灵活,可以对Excel表中的各个单元格进行用户所需的操作。

  1. openFileDialog = new OpenFileDialog();
  2. openFileDialog.Filter = "Excel files(*.xls)|*.xls";
  3. if(openFileDialog.ShowDialog()==DialogResult.OK)
  4. {
  5. FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
  6. string filePath = fileInfo.FullName;
  7. string connExcel = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0";
  8. try
  9. {
  10. OleDbConnection oleDbConnection = new OleDbConnection(connExcel);
  11. oleDbConnection.Open();
  12. //获取excel表
  13. DataTable dataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
  14. //获取sheet名,其中[0][1]...[N]: 按名称排列的表单元素
  15. string tableName = dataTable.Rows[0][2].ToString().Trim();
  16. tableName = "[" + tableName.Replace("'","") + "]";
  17. //利用SQL语句从Excel文件里获取数据
  18. //string query = "SELECT classDate,classPlace,classTeacher,classTitle,classID FROM " + tableName;
  19. string query = "SELECT 日期,开课城市,讲师,课程名称,持续时间 FROM " + tableName;
  20. dataSet = new DataSet();
  21. //OleDbCommand oleCommand = new OleDbCommand(query, oleDbConnection);
  22. //OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand);
  23. OleDbDataAdapter oleAdapter = new OleDbDataAdapter(query,connExcel);
  24. oleAdapter.Fill(dataSet,"gch_Class_Info");
  25. //从excel文件获得数据后,插入记录到SQL Server的数据表
  26. DataTable dataTable1 = new DataTable();
  27. SqlDataAdapter sqlDA1 = new SqlDataAdapter(@"SELECT classID, classDate,
  28. classPlace, classTeacher, classTitle, durativeDate FROM gch_Class_Info",sqlConnection1);
  29. //SqlCommandBuilder sqlCB1 = new SqlCommandBuilder(sqlDA1);
  30. sqlDA1.Fill(dataTable1);
  31. foreach(DataRow dataRow in dataSet.Tables["gch_Class_Info"].Rows)
  32. {
  33. DataRow dataRow1 = dataTable1.NewRow();
  34. dataRow1["classDate"] = dataRow["日期"];
  35. dataRow1["classPlace"] = dataRow["开课城市"];
  36. dataRow1["classTeacher"] = dataRow["讲师"];
  37. dataRow1["classTitle"] = dataRow["课程名称"];
  38. dataRow1["durativeDate"] = dataRow["持续时间"];
  39. dataTable1.Rows.Add(dataRow1);
  40. }
  41. Console.WriteLine("新插入 " + dataTable1.Rows.Count.ToString() + " 条记录");
  42. sqlDA1.Update(dataTable1);
  43. oleDbConnection.Close();
  44. }
  45. catch(Exception ex)
  46. {
  47. Console.WriteLine(ex.ToString());
  48. }
  49. }

方案二: 直接通过SQL语句执行SQL Server的功能函数将Excel文件转换到SQL Server数据库。

OpenFileDialog openFileDialog = new OpenFileDialog();

  1. openFileDialog.Filter = "Excel files(*.xls)|*.xls";
  2. SqlConnection sqlConnection1 = null;
  3. if(openFileDialog.ShowDialog()==DialogResult.OK)
  4. {
  5. string filePath = openFileDialog.FileName;
  6. sqlConnection1 = new SqlConnection();
  7. sqlConnection1.ConnectionString = "server=(local);integrated security=SSPI;initial catalog=Library";
  8. //import excel into SQL Server 2000
  9. /*string importSQL = "SELECT * into live41 FROM OpenDataSource" +
  10. "('Microsoft.Jet.OLEDB.4.0','Data Source=" + "\"" + "E:\\022n.xls" + "\"" +
  11. "; User ID=;Password=; Extended properties=Excel 5.0')...[Sheet1$]";*/
  12. //export SQL Server 2000 into excel
  13. string exportSQL = @"EXEC master..xp_cmdshell
  14. 'bcp Library.dbo.live41 out " + filePath + "-c -q -S" + "\"" + "\"" +
  15. " -U" + "\"" + "\"" + " -P" + "\"" + "\"" + "\'";
  16. try
  17. {
  18. sqlConnection1.Open();
  19. //SqlCommand sqlCommand1 = new SqlCommand();
  20. //sqlCommand1.Connection = sqlConnection1;
  21. //sqlCommand1.CommandText = importSQL;
  22. //sqlCommand1.ExecuteNonQuery();
  23. //MessageBox.Show("import finish!");
  24. SqlCommand sqlCommand2 = new SqlCommand();
  25. sqlCommand2.Connection = sqlConnection1;
  26. sqlCommand2.CommandText = exportSQL;
  27. sqlCommand2.ExecuteNonQuery();
  28. MessageBox.Show("export finish!");
  29. }
  30. catch(Exception ex)
  31. {
  32. MessageBox.Show(ex.ToString());
  33. }
  34. }
  35. if(sqlConnection1!=null)
  36. {
  37. sqlConnection1.Close();
  38. sqlConnection1 = null;
  39. }

方案三: 通过到入Excel的VBA dll,通过VBA接口获取Excel数据到DataSet

  1. OpenFileDialog openFile = new OpenFileDialog();
  2. openFile.Filter = "Excel files(*.xls)|*.xls";
  3. ExcelIO excelio = new ExcelIO();
  4. if(openFile.ShowDialog()==DialogResult.OK)
  5. {
  6. if(excelio!=null)
  7. excelio.Close();
  8. excelio = new ExcelIO(openFile.FileName);
  9. object[,] range = excelio.GetRange();
  10. excelio.Close();
  11. DataSet ds = new DataSet("xlsRange");
  12. int x = range.GetLength(0);
  13. int y = range.GetLength(1);
  14. DataTable dt = new DataTable("xlsTable");
  15. DataRow dr;
  16. DataColumn dc;
  17. ds.Tables.Add(dt);
  18. for(int c=1; c<=y; c++)
  19. {
  20. dc = new DataColumn();
  21. dt.Columns.Add(dc);
  22. }
  23. object[] temp = new object[y];
  24. for(int i=1; i<=x; i++)
  25. {
  26. dr = dt.NewRow();
  27. for(int j=1; j<=y; j++)
  28. {
  29. temp[j-1] = range[i,j];
  30. }
  31. dr.ItemArray = temp;
  32. ds.Tables[0].Rows.Add(dr);
  33. }
  34. dataGrid1.SetDataBinding(ds,"xlsTable");
  35. if(excelio!=null)
  36. excelio.Close();
  37. }

  当然还有其他一些方法,如遍历Excel文件中的数据然后构造sql语句,直接利用sql操作Excel文件导入数据库等,这些都是很常见的方法,因此就不再做收录了。最后说明下,以上的方法是我从网上找的源码并做了一定的修改,希望对大家有帮助。

将Excel文件数据导入到SqlServer数据库的三种方案的更多相关文章

  1. Excel表格数据导入到SQLServer数据库

    转载:http://blog.csdn.net/lishuangzhe7047/article/details/8797416 步骤: 1,选择要插入的数据库--右键--任务--导入数据 2,点击下一 ...

  2. 怎样把excel的数据导入到sqlserver2000数据库中

    在做程序的时候有时需要把excel数据导入到sqlserver2000中,以前没从外部导入过数据,今天刚做了一下导入数据,感觉还是蛮简单的,没做过之前还想着多么的复杂呢,下面就来分享一下我是如何把ex ...

  3. Excel表数据导入Sql Server数据库中

    Excel表数据导入Sql Server数据库的方法很多,这里只是介绍了其中一种: 1.首先,我们要先在test数据库中新建一个my_test表,该表具有三个字段tid int类型, tname nv ...

  4. java读取excel文件数据导入mysql数据库

    这是我来公司的第二周的一个小学习任务,下面是实现过程: 1.建立maven工程(方便管理jar包) 在pom.xml导入 jxl,mysql-connector 依赖 可以在maven仓库搜索 2.建 ...

  5. Excel文件数据导入到后台保存倒数据库

    后台代码数据解析: 方法一: (简单点) import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermo ...

  6. 使用navicat for sqlserver 把excel中的数据导入到sqlserver数据库

    以前记得使用excel向mysql中导入过数据,今天使用excel向sqlserver2005导入了数据,在此把做法记录一下 第一步:准备excel数据,在这个excel中有3个sheet,每个she ...

  7. 将 excel文件数据导入MySQL数据库中

    第一步:先将Excel文件另存为文本文件(制表符分割) 第二步:将生成的txt文件另存,并修改编码格式utf8; 第三步:将文件放到指定位置,或自己想要的位置: G:\city.txt 第四步:避免创 ...

  8. Excel 数据导入至Sqlserver 数据库中 ltrim&lpar;&rpar; 、rtrim&lpar;&rpar; 、replace&lpar;&rpar; 函数 依次空格无效问题

    今天导一些数据从Excel中至Sqlserver 数据库中,在做数据合并去重的时候发现,有两条数据一模一样,竟然没有进行合并: 最后发现有一条后面有个“空格”,正是因为这个“空格”让我抓狂许久,因为它 ...

  9. pl&sol;sql 如何将Excel文件数据导入oracle的数据表?

    1.准备导入数据的excel文件 注意:excel列名和数据表列名必须相同,excel文件sheet2和sheet3可以删除 1)excel文件格式 2)数据表格式 2.打开pl/sql ,找到工具- ...

随机推荐

  1. Linux学习之七——乱码的解决方案

    一.乱码的原因 乱码是编码不统一引起的,有下面一些地方需要注意 1. Linux 系统默认支持的语系数据:这与 /etc/sysconfig/i18n 有关:2. 你的终端界面 (bash) 的语系: ...

  2. 概念学习(Concept Learning)

    从特殊的训练样例中归纳出一般函数是机器学习的核心问题.一般函数是对理想目标函数的函数逼近(function approximation).简而言之,从特殊到普通.与此对应的是演绎推理(deductiv ...

  3. HDOJ&lpar;HDU&rpar; 2153 仙人球的残影&lpar;谜一样的题、、、&rpar;

    Problem Description 在美丽的HDU,有一名大三的同学,他的速度是众所周知的,跑100米仅仅用了2秒47,在他跑步过程中会留下残影的哎,大家很想知道他是谁了吧,他叫仙人球,既然名字这 ...

  4. 对于Web开发来说 8 个最好的跨平台编辑器

    1) Best Cross Platform IDE - Brackets Brackets是一个在前端Web开发和设计人员中最流行的开放源代码IDE/代码编辑器之中的一个.它拥有一些有用工具可以将H ...

  5. AutoTile 自动拼接(五) 学习与实践

    今天不讲 权值检索,考虑到后期 自动拼接 做出来 更好玩,操作更方便.所以 今天我 补充一节, 网格计算与操作. 具体就是这么个效果,和地图编辑器一样,不过图块还是没有自然的拼接,这个一定一定是 下一 ...

  6. VMware下安装Linux(CentOs6&period;3)操作系统

    VMware 10.0.2 CentOs 6.3 VMware的安装以及CentOs的下载比较简单,这里不再描述 1.创建新的虚拟机 2.选择典型 3.选择稍后安装操作系统 4.选择如图所示 5.虚拟 ...

  7. codeforces116B

    Little Pigs and Wolves CodeForces - 116B Once upon a time there were several little pigs and several ...

  8. myeclipse提示错误。

    Syntax error, parameterized types are only available if source level is 1.5 解决方法:编译器问题.注意myeclipse10 ...

  9. A:LinkedList实现了List接口; B: AbstractSet实现了Set接口; C: HashSet继承自AbstractSet基类; D: WeakMap继承自 AbstractMap

    List,Set,Map在java.util包下都是接口 List有两个实现类:ArrayList和LinkedListSet有两个实现类:HashSet和LinkedHashSetAbstractS ...

  10. hdu-2191(完全背包&plus;二进制优化模板)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2191 思路:完全背包模板 #include<iostream> #include<c ...