将Excel文件数据库导入SQL Server的三种方案//方案一: 通过OleDB方式获取Excel文件的数据,然后通过DataSet中转到SQL Server

openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel files(*.xls)|*.xls";

if(openFileDialog.ShowDialog()==DialogResult.OK)
{
    FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
    string filePath = fileInfo.FullName;
    string connExcel = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0";
    
    try
    {
        OleDbConnection oleDbConnection = new OleDbConnection(connExcel);
        oleDbConnection.Open();
        
        //获取excel表
        DataTable dataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

//获取sheet名,其中[0][1]...[N]: 按名称排列的表单元素
        string tableName = dataTable.Rows[0][2].ToString().Trim();
        tableName = "[" + tableName.Replace("'","") + "]";

//利用SQL语句从Excel文件里获取数据
        //string query = "SELECT classDate,classPlace,classTeacher,classTitle,classID FROM " + tableName;
        string query = "SELECT 日期,开课城市,讲师,课程名称,持续时间 FROM " + tableName;
        dataSet = new DataSet();

//OleDbCommand oleCommand = new OleDbCommand(query, oleDbConnection);
        //OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand);
        OleDbDataAdapter oleAdapter = new OleDbDataAdapter(query,connExcel);
        
        oleAdapter.Fill(dataSet,"gch_Class_Info");

//dataGrid1.DataSource = dataSet;
        //dataGrid1.DataMember = tableName;
        dataGrid1.SetDataBinding(dataSet,"gch_Class_Info");

//从excel文件获得数据后,插入记录到SQL Server的数据表
        DataTable dataTable1 = new DataTable();
        
        SqlDataAdapter sqlDA1 = new SqlDataAdapter(@"SELECT classID, classDate,
classPlace, classTeacher, classTitle, durativeDate FROM gch_Class_Info",sqlConnection1);
        
        SqlCommandBuilder sqlCB1 = new SqlCommandBuilder(sqlDA1);
        
        sqlDA1.Fill(dataTable1);

foreach(DataRow dataRow in dataSet.Tables["gch_Class_Info"].Rows)
        {
            DataRow dataRow1 = dataTable1.NewRow();
            
            dataRow1["classDate"] = dataRow["日期"];
            dataRow1["classPlace"] = dataRow["开课城市"];
            dataRow1["classTeacher"] = dataRow["讲师"];
            dataRow1["classTitle"] = dataRow["课程名称"];
            dataRow1["durativeDate"] = dataRow["持续时间"];

dataTable1.Rows.Add(dataRow1);
        }

Console.WriteLine("新插入 " + dataTable1.Rows.Count.ToString() + " 条记录");
        sqlDA1.Update(dataTable1);
        
        oleDbConnection.Close();

}
    catch(Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

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

OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel files(*.xls)|*.xls";

SqlConnection sqlConnection1 = null;

if(openFileDialog.ShowDialog()==DialogResult.OK)
{
    string filePath = openFileDialog.FileName;

sqlConnection1 = new SqlConnection();
    sqlConnection1.ConnectionString = "server=(local);integrated security=SSPI;initial catalog=Library";

//import excel into SQL Server 2000
    /*string importSQL = "SELECT * into live41 FROM OpenDataSource" + 
        "('Microsoft.Jet.OLEDB.4.0','Data Source=" + "/"" + "E://022n.xls" + "/"" + 
        "; User ID=;Password=; Extended properties=Excel 5.0')...[Sheet1$]";*/

//export SQL Server 2000 into excel
    string exportSQL = @"EXEC master..xp_cmdshell
'bcp Library.dbo.live41 out " + filePath + "-c -q -S" + "/"" + "/"" +
        " -U" + "/"" + "/"" + " -P" + "/"" + "/"" + "/'";
    
    try
    {
        sqlConnection1.Open();
        
        //SqlCommand sqlCommand1 = new SqlCommand();
        //sqlCommand1.Connection = sqlConnection1;
        //sqlCommand1.CommandText = importSQL;
        //sqlCommand1.ExecuteNonQuery();
        //MessageBox.Show("import finish!");
        
        SqlCommand sqlCommand2 = new SqlCommand();
        sqlCommand2.Connection = sqlConnection1;
        sqlCommand2.CommandText = exportSQL;
        sqlCommand2.ExecuteNonQuery();
        MessageBox.Show("export finish!");
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

if(sqlConnection1!=null)
{
    sqlConnection1.Close();
    sqlConnection1 = null;
}

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

OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Excel files(*.xls)|*.xls";

ExcelIO excelio = new ExcelIO();

if(openFile.ShowDialog()==DialogResult.OK)
{
    if(excelio!=null)
        excelio.Close();

excelio = new ExcelIO(openFile.FileName);
    object[,] range = excelio.GetRange();
    excelio.Close();

DataSet ds = new DataSet("xlsRange");

int x = range.GetLength(0);
    int y = range.GetLength(1);

DataTable dt = new DataTable("xlsTable");
    DataRow dr;
    DataColumn dc;
    
    ds.Tables.Add(dt);

for(int c=1; c<=y; c++)
    {
        dc = new DataColumn();
        dt.Columns.Add(dc);
    }
    
    object[] temp = new object[y];
    
    for(int i=1; i<=x; i++)
    {
        dr = dt.NewRow();

for(int j=1; j<=y; j++)
        {
            temp[j-1] = range[i,j];
        }
        
        dr.ItemArray = temp;
        ds.Tables[0].Rows.Add(dr);
    }

dataGrid1.SetDataBinding(ds,"xlsTable");
    
    if(excelio!=null)
        excelio.Close();
}

将Excel文件数据库导入SQL Server相关推荐

  1. net以execl做数据库_C#.NET Excel文件数据导入SQL Server数据库完整代码

    展开全部 在日常的项目中,Excel,Word,txt等格式的数62616964757a686964616fe58685e5aeb931333337626235据导入到数据库中是很常见 这里将分为.n ...

  2. 不用代码快速将Excel的数据导入SQL Server数据库中

    主要通过SQL Server的导入功能 直接写流程 1.首先获取一份符合格式的Excel表(能导入数据库Excel的格式是97-2003) 字段名就是你要导入数据库表的字段名(导入后这个表只作为临时表 ...

  3. 将数据库导入SQL Server里

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 开发工具与关键技术:VS 作者:

  4. 使用SSIS包将多个Excel文件中的数据导入SQL Server表中

    This article explores an SSIS package for importing multiple Excel files data into SQL Server tables ...

  5. 如何将数据从Excel文件导入SQL Server数据库

    There are many ways to import data from an Excel file to a SQL Server database using: 有多种方法可以使用以下方法将 ...

  6. Excel数字、文本混合列导入SQL Server出现的问题&解决办法

    版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明 http://annie-out.blogbus.com/logs/60276495.html Excel文件: 序号 姓名 内部电话 ...

  7. 从压缩文件将数据导入SQL Server

    介绍 (Introduction) I have seen many organizations receive data from various sources and import into S ...

  8. 将Excel数据导入SQL Server数据库

    遇到了一个需求,需要将Excel中的数据导入SQL Server数据库中,当然,不是使用企业管理器之类的直接导入数据的那种,而是要做到程序中.本来我最初的考虑是将Excel中的数据读到dataset中 ...

  9. python怎么导入sql数据库,##使用python将excel表中数据导入sql server数据库

    如何用python将excel数据导入到postgresql数据库中 把excel表格另存为csv文件 python将exce文件含有多个sheet同时l导入sqlserver数据库 需要使用xlrd ...

最新文章

  1. 线性O(N)时间复杂度求素数 , 筛法
  2. [JLOI2014]聪明的燕姿(搜索)
  3. 计算机操作系统课后题答案第三章,计算机操作系统教程习题与实验指导(第3版)...
  4. c语言流水灯小程序,流水灯小程序.doc
  5. java 画砖块,钢笔画入门:教你画砖块
  6. sqlmap绕过d盾_Waf功能、分类与绕过
  7. [react] 怎么定时更新一个组件?
  8. css 块元素、内联元素、内联块元素
  9. Web框架——Flask系列之session机制(十六)
  10. SDUT 1149 勾股定理第一弹 勾股数
  11. python中全部注释_Python中的注释
  12. Linux编写脚本nsum求和,shell脚本学习与总结
  13. 测试眼睛距离的手机软件,早教APP哪款护眼功能最完善?这几款可检测宝宝坐姿和观看距离...
  14. pyhon编码问题之由 u'\uxxx' 转 \uxxx
  15. 【数学建模和matlab】反思与总结(1)
  16. STM32WL LoRaWAN节点设备学习记录(一)
  17. Reactor模式简单实现与理解
  18. 浅析深度学习中优化方法
  19. linux while 多个条件,Shell语法—— while 条件语句
  20. 36 岁捧走图灵碗!80 岁算法大师高德纳要在 105 岁完结《计算机程序设计艺术》...

热门文章

  1. 高版本linux安装gamit,求助(Ubuntu14.1上安装GAMIT10.5过程中错误提示如下)
  2. copy 修改时间_DAY5-step3 Python用shutil.copy(), shutil.copystat()复制文件
  3. deepsort原理快速弄懂——时效比最高的
  4. laravel carbon 格式化日期_Laravel 编码实践分享
  5. MonoRec:无需激光雷达,只需单个相机就可以实现三维场景的稠密重建
  6. 剑指offer:面试题19. 正则表达式匹配
  7. 设置centos默认启动命令行(不启动图形界面)
  8. 在CentOS 6.3 64bit上利用iptables开放指定端口的方法
  9. ubuntu 14.04 64 bit上开启nscd服务缓存加速及清除dns缓存
  10. Linux从程序到进程