将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 ...
随机推荐
- 洛谷 P1044 栈
题目背景 栈是计算机中经典的数据结构,简单的说,栈就是限制在一端进行插入删除操作的线性表. 栈有两种最重要的操作,即pop(从栈顶弹出一个元素)和push(将一个元素进栈). 栈的重要性不言自明,任何 ...
- [洛谷P3444] [POI2006]ORK-Ploughing
洛谷题目链接[POI2006]ORK-Ploughing 题目描述 Byteasar, the farmer, wants to plough his rectangular field. He ca ...
- mysql binlog日志手动清除
purge binary logs to 'mysql-bin.000050'; set global expire_logs_days=7; flush logs;
- 【Foreign】登山 [DP][数学]
登山 Time Limit: 10 Sec Memory Limit: 256 MB Description 恶梦是一个登山爱好者,今天他来到了黄山 俗话说的好,不走回头路.所以在黄山,你只能往前走 ...
- DotNETCore 学习笔记 MVC视图
Razor Syntax Reference Implicit Razor expressions <p>@DateTime.Now</p> <p>@DateTim ...
- poj 2762 tarjan缩点+拓扑序
2013-09-08 10:00 var m, n :longint; t :longint; f, last :..] of longint; pre, other :..] of longint; ...
- kolakoski序列
搜狐笔试=.= 当时少想一个slow的指针..呜呜呜哇的一声哭出来 function kolakoski(token0, token1) { token0 = token ...
- php中的parse_ini_file函数
作用:parse_ini_file() 函数解析一个配置文件,并以数组的形式返回其中的设置 格式:parse_ini_file(file,true)// (第二个参数为可选参数.如果设置为 true, ...
- CTF两个经典的文件包含案例
案例一URL:http://120.24.86.145:8003/代码 <?php include "waf.php"; include "flag.php&quo ...
- Laravel 5.2 整合 Uploadify 上传图片
前端: <!-- 引入CSS.JS --> <link rel="stylesheet" type="text/css" href=" ...