下载本文档
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
C#将Excel数据表导⼊SQL数据库的两种⽅法(⾼效率)⽅法⼀:使⽤bcp,也就是System.Data.SqlClient.SqlBulkCopy类来实现。usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;usingSystem.Data.OleDb;namespaceTest1{publicpartialclassForm4:Form{publicForm4(){InitializeComponent();}privatevoidbutton1_Click(objectsender,EventArgse){//connStr="Server=USER-20180315FD;initialcatalog=AliDataTech;userid=sa;password=wxd123456;ConnectTimeout=5";//测试,将excel中的student导⼊到sqlserver的db_test中,如果sql中的数据表不存在则创建//stringconnString="server=(local);uid=sa;pwd=wxd123456;database=db_test";stringconnString="Server=USER-20180315FD;initialcatalog=db_test;userid=sa;password=wxd123456;ConnectTimeout=5";System.Windows.Forms.OpenFileDialogfd=newOpenFileDialog();if(fd.ShowDialog()==DialogResult.OK){TransferData(fd.FileName,"student",connString);}}publicvoidTransferData(stringexcelFile,stringsheetName,stringconnectionString){DataSetds=newDataSet();try{//获取全部数据stringstrConn="Provider=Microsoft.Jet.OLEDB.4.0;"+"DataSource="+excelFile+";"+"ExtendedProperties=Excel8.0;";OleDbConnectionconn=newOleDbConnection(strConn);conn.Open();stringstrExcel=OleDbDataAdaptermyCommand=null;strExcel=string.Format("select*from[{0}$]",sheetName);myCommand=newOleDbDataAdapter(strExcel,strConn);myCommand.Fill(ds,sheetName);//如果⽬标表不存在则创建,excel⽂件的第⼀⾏为列标题,从第⼆⾏开始全部都是数据记录stringstrSql=string.Format("ifnotexists(select*fromsysobjectswherename='{0}')createtable{0}(",sheetName);//以sheetName为表名foreach(System.Data.DataColumncinds.Tables[0].Columns){strSql+=string.Format("[{0}]varchar(255),",c.ColumnName);}strSql=strSql.Trim(',')+")";using(System.Data.SqlClient.SqlConnectionsqlconn=newSystem.Data.SqlClient.SqlConnection(connectionString)){sqlconn.Open();System.Data.SqlClient.SqlCommandcommand=sqlconn.CreateCommand();command.CommandText=strSql;command.ExecuteNonQuery();sqlconn.Close();}//⽤bcp导⼊数据//excel⽂件中列的顺序必须和数据表的列顺序⼀致,因为数据导⼊时,是从excel⽂件的第⼆⾏数据开始,不管数据表的结构是什么样的,反正就using(System.Data.SqlClient.SqlBulkCopybcp=newSystem.Data.SqlClient.SqlBulkCopy(connectionString)){bcp.SqlRowsCopied+=newSystem.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);bcp.BatchSize=1;//每次传输的⾏数bcp.NotifyAfter1;//进度提⽰的⾏数bcp.DestinationTableName=sheetName;//⽬标表bcp.WriteToServer(ds.Tables[0]);}}catch(Exceptionex){System.Windows.Forms.MessageBox.Show(ex.Message);}}//进度显⽰voidbcp_SqlRowsCopied(objectsender,System.Data.SqlClient.SqlRowsCopiedEventArgse){this.Text=e.RowsCopied.ToString();textBox1.Text=e.RowsCopied.ToString();textBox1.Update();this.Update();}privatevoidprogressBar1_Click(objectsender,EventArgse){}}}⽅法⼆:usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;usingSystem.Data.OleDb;usingSystem.Data.SqlClient;namespaceTest1{publicpartialclassForm5:Form{publicForm5(){InitializeComponent();}DataTabledt=newDataTable();//stringconnString="Server=USER-20180315FD;initialcatalog=db_test;userid=sa;password=wxd123456;ConnectTimeout=5";stringconnString="Server=USER-20180315FD;initialcatalog=db_test;userid=sa;password=wxd123456;ConnectTimeout=5";SqlConnectionconn;privatevoidbutton1_Click(objectsender,EventArgse){System.Windows.Forms.OpenFileDialogfd=newOpenFileDialog();if(fd.ShowDialog()==DialogResult.OK){stringfileName=fd.FileName;bind(fileName);}}privatevoidbind(stringfileName){stringstrConn="Provider=Microsoft.Jet.OLEDB.4.0;"+"DataSource="+fileName+";"+"ExtendedProperties='Excel8.0;HDR=Yes;IMEX=1'";OleDbDataAdapterda=newOleDbDataAdapter("SELECT*FROM[student$]",strConn);DataSetds=newDataSet();try{da.Fill(ds);dt=ds.Tables[0];this.dataGridView1.DataSource=dt;}catch(Exceptionerr){MessageBox.Show("操作失败!"+err.ToString());}}//将Datagridview1的记录插⼊到数据库privatevoidbutton2_Click(objectsender,EventArgse){conn=newSqlConnection(connString);conn.Open();if(dataGridView1.Rows.Count>0){DataRowdr=null;for(inti=0;i<dt.Rows.Count;i++){dr=dt.Rows[i];insertToSql(dr);}conn.Close();MessageBox.Show("导⼊成功!");}else{MessageBox.Show("没有数据!");}}privatevoidinsertToSql(DataRowdr){//excel表中的列名和数据库中的列名⼀定要对应stringname=dr["StudentName"].ToString();stringsex=dr["Sex"].ToString();stringno=dr["StudentIDNO"].ToString();stringmajor=dr["Major"].ToString();stringsql="insertintostudentvalues('"+name+"','"+sex+"','"+no+"','"+major+"')";SqlCommandcmd=newSqlCommand(sql,conn);cmd.ExecuteNonQuery();}}}.9Form5 l=1恤button! butt泣宝贝名称宝贝名称搜索类型流里来谏展现里^►曰期18月芽儿粗踉短2019/1/12 18DYV28匕CI?ICIC(|"
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026年杭州西湖区青少年宫诚聘教师(非事业)考试参考题库及答案解析
- 智能机器:数字时代的工业变革核心力量
- 2026四川省第三人民医院高层次人才、成熟人才招聘12人考试参考试题及答案解析
- 2026年1月西安唐城医院招聘(48人)考试参考试题及答案解析
- 2026湖南邵阳邵东市市直事业单位人才引进62人笔试备考题库及答案解析
- 2026福建三明市清流县应急管理局招聘县森林消防大队劳务派遣人员1人考试备考题库及答案解析
- 2026年河南医药大学诚聘研究生辅导员10名考试备考试题及答案解析
- 食品饮料:白酒破而后立大众品顺势而为-
- 2026山东枣庄市台儿庄区面向2017年前招募仍在镇(街)工作“三支一扶”人员招聘镇(街)事业单位人员考试备考题库及答案解析
- 2026重庆九洲智造科技有限公司招聘研发工程师10人考试备考试题及答案解析
- 中海大海洋地质学课件第4章河口与海岸-3第十二讲
- 招标人主体责任履行指引
- 财务审计工作程序及风险防范措施
- (人力资源管理专科)毕业论文
- 刮板链式运输机三级圆锥齿轮减速器设计
- 解读(2025年版)输卵管积水造影诊断中国专家共识
- (正式版)DB50∕T 1879-2025 《刨猪宴菜品烹饪技术规范》
- 高职院校技能大赛指导手册
- 轨道交通废弃物处理-洞察及研究
- 2024年一建网络图案例专题
- 智齿拔除术课件
评论
0/150
提交评论