博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何高效的将excel导入sqlserver?(转)
阅读量:7074 次
发布时间:2019-06-28

本文共 2569 字,大约阅读时间需要 8 分钟。

 大部分人都知道用oledb来读取数据到dataset,但是读取之后怎么处理dataset就千奇百怪了。很多人通过循环来拼接sql,这样做不但容易出错而且效率低下,System.Data.SqlClient.SqlBulkCopy 对于新手来说还是比较陌生的,这个就是传说中效率极高的bcp,6万多数据从excel导入到sql只需要4.5秒。

None.gif
using
 System;
None.gif
using
 System.Data;
None.gif
using
 System.Windows.Forms;
None.gif
using
 System.Data.OleDb;
None.gif
namespace
 WindowsApplication2
ExpandedBlockStart.gif
{
InBlock.gif    
public partial class
 Form1 : Form
ExpandedSubBlockStart.gif    
{
InBlock.gif        
public
 Form1()
ExpandedSubBlockStart.gif        
{
InBlock.gif            InitializeComponent();
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif        
private void button1_Click(object sender, EventArgs e)
ExpandedSubBlockStart.gif        
{
InBlock.gif            
//测试,将excel中的sheet1导入到sqlserver中
InBlock.gif
            string connString = "server=localhost;uid=sa;pwd=sqlgis;database=master";
InBlock.gif            System.Windows.Forms.OpenFileDialog fd 
= new
 OpenFileDialog();
InBlock.gif            
if (fd.ShowDialog() ==
 DialogResult.OK)
ExpandedSubBlockStart.gif            
{
InBlock.gif                TransferData(fd.FileName, 
"sheet1"
, connString);
ExpandedSubBlockEnd.gif            }
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif        
public void TransferData(string excelFile, string sheetName, string connectionString)
ExpandedSubBlockStart.gif        
{
InBlock.gif            DataSet ds 
= new
 DataSet();
InBlock.gif            
try
ExpandedSubBlockStart.gif            
{
InBlock.gif                
//获取全部数据
InBlock.gif
                string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFile + ";" + "Extended Properties=Excel 8.0;";
InBlock.gif                OleDbConnection conn 
= new
 OleDbConnection(strConn);
InBlock.gif                conn.Open();
InBlock.gif                
string strExcel = ""
;
InBlock.gif                OleDbDataAdapter myCommand 
= null
;
InBlock.gif                strExcel 
= string.Format("select * from [{0}$]"
, sheetName);
InBlock.gif                myCommand 
= new
 OleDbDataAdapter(strExcel, strConn);
InBlock.gif                myCommand.Fill(ds, sheetName);
InBlock.gif
InBlock.gif                
//如果目标表不存在则创建
InBlock.gif
                string strSql = string.Format("if object_id('{0}') is null create table {0}(", sheetName);
InBlock.gif                
foreach (System.Data.DataColumn c in ds.Tables[0
].Columns)
ExpandedSubBlockStart.gif                
{
InBlock.gif                    strSql 
+= string.Format("[{0}] varchar(255),"
, c.ColumnName);
ExpandedSubBlockEnd.gif                }
InBlock.gif                strSql 
= strSql.Trim(',') + ")";
InBlock.gif
InBlock.gif                
using (System.Data.SqlClient.SqlConnection sqlconn = new
 System.Data.SqlClient.SqlConnection(connectionString))
ExpandedSubBlockStart.gif                
{
InBlock.gif                    sqlconn.Open();
InBlock.gif                    System.Data.SqlClient.SqlCommand command 
=
 sqlconn.CreateCommand();
InBlock.gif                    command.CommandText 
=
 strSql;
InBlock.gif                    command.ExecuteNonQuery();
InBlock.gif                    sqlconn.Close();
ExpandedSubBlockEnd.gif                }
InBlock.gif                
//用bcp导入数据
InBlock.gif
                using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connectionString))
ExpandedSubBlockStart.gif                
{
InBlock.gif                    bcp.SqlRowsCopied 
+= new
 System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
InBlock.gif                    bcp.BatchSize 
= 100;//每次传输的行数
InBlock.gif
                    bcp.NotifyAfter = 100;//进度提示的行数
InBlock.gif
                    bcp.DestinationTableName = sheetName;//目标表
InBlock.gif
                    bcp.WriteToServer(ds.Tables[0]);
ExpandedSubBlockEnd.gif                }
ExpandedSubBlockEnd.gif            }
InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gif            
{
InBlock.gif                System.Windows.Forms.MessageBox.Show(ex.Message);
ExpandedSubBlockEnd.gif            }
InBlock.gif
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif        
//进度显示
InBlock.gif
        void bcp_SqlRowsCopied(object sender, System.Data.SqlClient.SqlRowsCopiedEventArgs e)
ExpandedSubBlockStart.gif        
{
InBlock.gif            
this.Text =
 e.RowsCopied.ToString();
InBlock.gif            
this
.Update();
ExpandedSubBlockEnd.gif        }
InBlock.gif
InBlock.gif
ExpandedSubBlockEnd.gif    }
ExpandedBlockEnd.gif}
 

 

  上面的TransferData基本可以直接使用,如果要考虑周全的话,可以用oledb来获取excel的表结构,并且加入ColumnMappings来设置对照字段,这样效果就完全可以做到和sqlserver的dts相同的效果了。

本文转自 你听海是不是在笑 博客园博客,原文链接:http://www.cnblogs.com/nuaalfm/archive/2009/04/04/1429626.html
  ,如需转载请自行联系原作者
你可能感兴趣的文章
TCP端口状态说明ESTABLISHED、TIME_WAIT
查看>>
I.MX6 android 4.2 源码下载
查看>>
md5sum 生成 经md5加密后的字符串
查看>>
PowerShell应用之-批量执行SQL脚本
查看>>
职场加薪步步高升的五大法则
查看>>
增删主键及修改表名
查看>>
Gson库使用-排序字段(ExclusionStrategy)或者修改(FieldNamingStrategy)字段
查看>>
NTFS For Mac 的特点有哪些
查看>>
新技能,利用Reflector来修改dll引用
查看>>
Java编程的逻辑 (1) - 数据和变量
查看>>
我的屌丝giser成长记-研一篇(下)
查看>>
raft 分布式协议 -- mongodb
查看>>
[TypeScript] Using Lodash in TypeScript with Typings and SystemJS
查看>>
ASP.Net MVC开发基础学习笔记(1):走向MVC模式
查看>>
虚函数可不可以是内联函数
查看>>
据说看完这21个故事的人,30岁前都成了亿万富翁
查看>>
HDOJ-4505 小Q系列故事——电梯里的爱情
查看>>
【转】Navigation Drawer(导航抽屉)
查看>>
Linux Shell常用技巧(十)
查看>>
【从零之三(更)】自定义类中调用讯飞语音包错误解决办法
查看>>