将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 ...
随机推荐
- (转)如何在windows 2008 安装IIS
首先声明本文转自http://www.pc6.com/infoview/Article_54712.html ,作者为清晨 转载的原因有两个,一是怕原文挂了,而是打算写一下在阿里云部署django的文 ...
- AngularJs 中的CheckBox前后台交互
前台页面: <div class="form-group"> <label for="CompanyName" class="col ...
- java 错误: 找不到或无法加载主类解决方法
1.配置好jdk与jre环境变量路径 https://www.cnblogs.com/xch-yang/p/7629351.html 2.在编译和运行的时候需要注意如下格式.
- poj 1797
2013-09-08 09:48 最大生成树,输出生成树中最短的边儿即可 或者对边儿排序,二份答案+BFS判断是否1连通N 时间复杂度都是O(NlogN)的 附最大生成树pascal代码 //By B ...
- SpringBoot工程目录配置
Spring Boot建议的目录结果如下: root package结构:com.example.myproject com +- example +- myproject +- Applicat ...
- Linux中断(interrupt)子系统之二:arch相关的硬件封装层【转】
转自:http://blog.csdn.net/droidphone/article/details/7467436 Linux的通用中断子系统的一个设计原则就是把底层的硬件实现尽可能地隐藏起来,使得 ...
- 【Android XML】Android XML 转 Java Code 系列之 介绍(1)
最近在公司做一个项目,需要把Android界面打包进jar包给客户使用.对绝大部分开发者来说,Android界面的布局以XML文件为主,并辅以少量Java代码进行动态调整.而打包进jar包的代码,意味 ...
- U-Boot启动过程完全分析<转>
转载自:http://www.cnblogs.com/heaad/archive/2010/07/17/1779829.html 1.1 U-Boot工作过程 U-Boot启动内核的过程可 ...
- 2015多校第8场 HDU 5382 GCD?LCM! 数论公式推导
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5382 题意:函数lcm(a,b):求两整数a,b的最小公倍数:函数gcd(a,b):求两整数a,b的最 ...
- c#中char、string转换为十六进制byte的浅析
问题引出: string转换为byte(十六进制) static void Main(string[] args) { "; byte[] b = Encoding.Default.GetB ...