将excel中的sheet1导入到sqlserver中
方式一:
实现在c#中可高效的将excel数据导入到sqlserver数据库中,很多人通过循环来拼接sql,这样做不但容易出错而且效率低下,最好的办法是使用bcp,也就是System.Data.SqlClient.SqlBulkCopy 类来实现。
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
{
public
partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//测试,将excel中的student导入到sqlserver的db_test中,如果sql中的数据表不存在则创建
string connString = "server = (local); uid = sa; pwd = sa; database
= db_test";
           
System.Windows.Forms.OpenFileDialog fd = new
OpenFileDialog();  
           
if (fd.ShowDialog() ==
DialogResult.OK)  
           
{
               
TransferData(fd.FileName, "student", connString);
           
}  
       
}  
public void TransferData(string excelFile, string sheetName, string
connectionString)
{
DataSet ds = new DataSet();
try
{
//获取全部数据
string strConn = "Provider = Microsoft.Jet.OLEDB.4.0;" + "Data
Source=" + excelFile + ";" + "Extended Properties = Excel
8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand =
null;
strExcel = string.Format("select * from [{0}$]", sheetName);
myCommand = new OleDbDataAdapter(strExcel, strConn);
myCommand.Fill(ds, sheetName);
//如果目标表不存在则创建,excel文件的第一行为列标题,从第二行开始全部都是数据记录
string strSql = string.Format("if not exists(select * from
sysobjects where name = '{0}') create table {0}(",
sheetName);
//以sheetName为表名
foreach (System.Data.DataColumn c in ds.Tables[0].Columns)
{
strSql += string.Format("[{0}] varchar(255),",
c.ColumnName);
}
strSql = strSql.Trim(',') +
")";
using (System.Data.SqlClient.SqlConnection sqlconn = new
System.Data.SqlClient.SqlConnection(connectionString))
{
                   
sqlconn.Open();  
                   
System.Data.SqlClient.SqlCommand command =
sqlconn.CreateCommand();  
                   
command.CommandText =
strSql;  
                   
command.ExecuteNonQuery();
sqlconn.Close();
               
}  
               
//用bcp导入数据  
               
//excel文件中列的顺序必须和数据表的列顺序一致,因为数据导入时,是从excel文件的第二行数据开始,不管数据表的结构是什么样的,反正就是第
一列的数据会插入到数据表的第一列字段中,第二列的数据插入到数据表的第二列字段中,以此类推,它本身不会去判断要插入的数据是对应数据表中哪一个字段的
using (System.Data.SqlClient.SqlBulkCopy bcp = new
System.Data.SqlClient.SqlBulkCopy(connectionString))
{  
                   
bcp.SqlRowsCopied += new
System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
bcp.BatchSize =
100;//每次传输的行数  
                   
bcp.NotifyAfter =
100;//进度提示的行数  
                   
bcp.DestinationTableName =
sheetName;//目标表  
                   
bcp.WriteToServer(ds.Tables[0]);
               
}  
           
}  
           
catch (Exception ex)  
           
{  
               
System.Windows.Forms.MessageBox.Show(ex.Message);
}
       
}  
 
       
//进度显示  
       
void bcp_SqlRowsCopied(object sender,
System.Data.SqlClient.SqlRowsCopiedEventArgs
e)  
       
{  
           
this.Text =
e.RowsCopied.ToString();  
           
this.Update();  
       
} 
   
}  
}
方式二:
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
{
public
partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
DataTable dt = new DataTable();
string connString = "server = (local); uid = sa; pwd = sa; database
= db_test";
SqlConnection conn;
private void button1_Click(object sender, EventArgs e)
{
System.Windows.Forms.OpenFileDialog fd = new
OpenFileDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
string fileName = fd.FileName;
bind(fileName);
}
}
private void bind(string fileName)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + fileName + ";" +
"Extended Properties='Excel 8.0; HDR=Yes; IMEX=1'";
OleDbDataAdapter da = new OleDbDataAdapter("SELECT
* FROM [student$]", strConn);
DataSet ds = new DataSet();
try
{
da.Fill(ds);
dt = ds.Tables[0];
this.dataGridView1.DataSource = dt;
}
catch (Exception err)
{
MessageBox.Show("操作失败!" + err.ToString());
}
}
//将Datagridview1的记录插入到数据库
private void button2_Click(object sender, EventArgs e)
{
conn = new SqlConnection(connString);
conn.Open();
if (dataGridView1.Rows.Count > 0)
{
DataRow dr = null;
for (int i = 0; i < dt.Rows.Count; i++)
{
dr = dt.Rows[i];
insertToSql(dr);
}
conn.Close();
MessageBox.Show("导入成功!");
}
else
{
MessageBox.Show("没有数据!");
}
}
private void insertToSql(DataRow dr)
{
//excel表中的列名和数据库中的列名一定要对应
string name = dr["StudentName"].ToString();
string sex = dr["Sex"].ToString();
string no = dr["StudentIDNO"].ToString();
string major = dr["Major"].ToString();
string sql = "insert into student values('" + name + "','" + sex +
"','" + no + "','" + major
+"')";
SqlCommand cmd = new SqlCommand(sql,
conn);
cmd.ExecuteNonQuery();
       
}
    }
}
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsApplication2
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
      //测试,将excel中的sheet1导入到sqlserver中
      string connString =
"server=localhost;uid=sa;pwd=sqlgis;database=master";
      System.Windows.Forms.OpenFileDialog fd = new
OpenFileDialog();
      if (fd.ShowDialog() == DialogResult.OK)
      {
        TransferData(fd.FileName, "sheet1", connString);
      }
    }
    public void TransferData(string excelFile, string sheetName,
string connectionString)
    {
      DataSet ds = new DataSet();
      try
      {
        //获取全部数据
        string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + excelFile + ";" + "Extended Properties=Excel
8.0;";
        OleDbConnection conn = new OleDbConnection(strConn);
        conn.Open();
        string strExcel = "";
        OleDbDataAdapter myCommand = null;
        strExcel = string.Format("select * from [{0}$]",
sheetName);
        myCommand = new OleDbDataAdapter(strExcel, strConn);
        myCommand.Fill(ds, sheetName);
        //如果目标表不存在则创建
        string strSql = string.Format("if
object_id('{0}') is null
create table {0}(", sheetName);
        foreach (System.Data.DataColumn c in
ds.Tables[0].Columns)
        {
          strSql += string.Format("[{0}] varchar(255),",
c.ColumnName);
        }
        strSql =
strSql.Trim(',') +
")";
        using (System.Data.SqlClient.SqlConnection sqlconn = new
System.Data.SqlClient.SqlConnection(connectionString))
        {
          sqlconn.Open();
          System.Data.SqlClient.SqlCommand command =
sqlconn.CreateCommand();
          command.CommandText = strSql;
          command.ExecuteNonQuery();
          sqlconn.Close();
        }
        //用bcp导入数据
        using (System.Data.SqlClient.SqlBulkCopy bcp = new
System.Data.SqlClient.SqlBulkCopy(connectionString))
        {
          bcp.SqlRowsCopied += new
System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
          bcp.BatchSize = 100;//每次传输的行数
          bcp.NotifyAfter = 100;//进度提示的行数
          bcp.DestinationTableName = sheetName;//目标表
          bcp.WriteToServer(ds.Tables[0]);
                       
sbc.DestinationTableName = "mobile_black "; //服务器上目标表的名称
sbc.BulkCopyTimeout = 180; //设置允许超时时间为100秒
sbc.ColumnMappings.Add("mobile", "mobile"); //本地表和目标表列名
sbc.ColumnMappings.Add("ts_id", "ts_id"); //如果表有多个字段,下面继续添加
sbc.WriteToServer(dt);//插入数据
result = true;
        }
      }
      catch (Exception ex)
      {
        System.Windows.Forms.MessageBox.Show(ex.Message);
      }
    }
    //进度显示
    void bcp_SqlRowsCopied(object sender,
System.Data.SqlClient.SqlRowsCopiedEventArgs e)
    {
      this.Text = e.RowsCopied.ToString();
      this.Update();
    }
  }
}
主要代码:
System.Data.SqlClient.SqlBulkCopy类,让大数量插入到MSSQL数据库中可以很快搞定。
项目中一个表100W条数据,普通SQL插入语句,花了10多分钟。
使用System.Data.SqlClient.SqlBulkCopy插入,只用了几秒钟。
下面是主要的代码:
- //省略连接字符串
 - SqlConnection conn = new
SqlConnection("....."); - conn.Open();
 - //初始化类
 - using
(System.Data.SqlClient.SqlBulkCopy sqlBC =
new
System.Data.SqlClient.SqlBulkCopy(conn)) - {
 - //获取需要导入的数据表
 - DataTable dt = GetDataTable();
 - //每10W条数据一个事物
 - sqlBC.BatchSize = 100000;
 - //超时时间
 - sqlBC.BulkCopyTimeout = 60;
 - //表名Users
 - sqlBC.DestinationTableName =
"dbo.Users"; - //字段对应,分表为原数据表字段名,和导入数据库的字段名
 - sqlBC.ColumnMappings.Add("Access_ID",
"MSSQL_ID"); - sqlBC.ColumnMappings.Add("Access_Name",
"MSSQL_Name"); - //sqlBC.ColumnMappings.Add("Access_...",
"MSSQL_..."); - //sqlBC.ColumnMappings.Add("Access_...",
"MSSQL_..."); - //导入到数据库
 - sqlBC.WriteToServer(dt);
 
将excel中的sheet1导入到sqlserver中的更多相关文章
- excel文件与txt文件互转,并且把excel里的数据导入到oracle中
		
一.excel文件转换成txt文件的步骤 a.首先要把excel文件转换成txt文件 1.Excel另存为中已经包含了TXT格式,所以我们可以直接将Excel表格另存为TXT格式,但是最后的效果好像不 ...
 - C# 将List中的数据导入csv文件中
		
//http://www.cnblogs.com/mingmingruyuedlut/archive/2013/01/20/2849906.html C# 将List中的数据导入csv文件中 将数 ...
 - 如何将数据库中的数据导入到Solr中
		
要使用solr实现网站中商品搜索,需要将mysql数据库中数据在solr中创建索引. 1.需要在solr的schema.xml文件定义要存储的商品Field. 商品表中的字段为: 配置内容是: < ...
 - MyEclipse中的项目导入到Eclipse中运行的错误解决
		
之前用的myEclipse,后来把项目导入eclipse发现报错,将MyEclipse中的项目导入到Eclipse中运行,不注意一些细节,会造成无法运行的后果.下面就说说具体操作:导入后出现如下错误: ...
 - sqlserver怎么将excel表的数据导入到数据库中
		
在数据库初始阶段,我们有些数据在EXCEL中做好之后,需要将EXCEL对应列名(导入后对应数据库表的字段名),对应sheet(改名为导入数据库之后的表名)导入指定数据库, 相当于导入一张表的整个数据. ...
 - 将*.sql数据库脚本导入到sqlserver中(sql文件导入sqlserver)
		
在SqlServer中这个是用生成sql脚本生成的 要是在导入数据库用数据导入/导出向导导不进去 其实要用查询分析器来打开sql文件 然后执行就可以了
 - python将oracle中的数据导入到mysql中。
		
一.导入表结构.使用工具:navicate premium 和PowerDesinger 1. 先用navicate premium把oracle中的数据库导出为oracle脚本. 2. 在Power ...
 - 使用navicat for sqlserver 把excel中的数据导入到sqlserver数据库
		
以前记得使用excel向mysql中导入过数据,今天使用excel向sqlserver2005导入了数据,在此把做法记录一下 第一步:准备excel数据,在这个excel中有3个sheet,每个she ...
 - excel数据导入到sqlserver中---------工作笔记
		
调用页面: using System; using System.Collections.Generic; using System.Linq; using System.Web; using Sys ...
 
随机推荐
- C++ 什么是多态
			
一.什么是多态(Polymorphism) 多态(Polymorphism)是面向对象(Object-Oriented,OO)思想"三大特征"之一,其余两个分别是封装(Encaps ...
 - Java中的String为什么是不可变的? — String源码分析
			
原文地址:http://www.importnew.com/16817.html 什么是不可变对象? 众所周知, 在Java中, String类是不可变的.那么到底什么是不可变的对象呢? 可以这样认为 ...
 - Win7 安装配置 nexus3.7.1
			
安装准备: nexus3.7.1 环境准备: maven.jdk 解压nexus目录结构为: E:\nexus-3.7.1-02 配置环境变量: 启动: nexus.exe /run
 - 【Android】完善Android学习(三:API 3.0)
			
备注:之前Android入门学习的书籍使用的是杨丰盛的<Android应用开发揭秘>,这本书是基于Android 2.2API的,目前Android已经到4.4了,更新了很多的API,也增 ...
 - Jenkenis报错:该jenkins实例似乎已离线[转]
			
解决方法: 安装插件那个页面,就是提示你offline的那个页面,不要动.然后打开一个新的tab,输入网址http://localhost:8080/pluginManager/advanced. 这 ...
 - el-date-picker 日期格式化 yyyy-MM-dd
			
<el-date-picker format="yyyy-MM-dd" v-model="dateValue" type="date" ...
 - window对象的方法和属性汇总
			
window对象有以下方法: open close alert confirm prompt setTimeout clearTimeout setInterval clearInterval mov ...
 - ie8下trim失效
			
1.ie8下使用trim失效 trim可以除去字符串两侧的空白字符,但ie8并不支持 2.解决方案 String.prototype.trim = function () { return this ...
 - 一个python拖库字段的小脚本
			
import requests import re all_column = dict() all_db = "db_zf,dg_activity,dg_activity_log,dg_ad ...
 - html meta标签作用
			
1.概要 标签提供关于HTML文档的元数据.元数据不会显示在页面上,但是对于机器是可读的.它可用于浏览器(如何显示内容或重新加载页面),搜索引擎(关键词),或其他web服务. 必要属性: conten ...