ASP实现将Excel表格数据批量导入到SQLServer数据库
ASP编程语言把EXCEL数据导入SQL SERVER 中

</tr>
<tr>
<td width=&uot;25%&uot; align=&uot;right&uot;>请选择数据源:</td>
<td width=&uot;75%&uot;><input type=&uot;file&uot; name=&uot;File&uot; size=&uot;40&uot; title=&uot;请选择需要导出的Excel文件&uot;></td>
</tr>
<tr>
<td align=&uot;right&uot;>请选择目标表:</td>
<td><SELECT NAME=&uot;Table&uot; title=&uot;请选择需要导入数据的表&uot;>
<table width=&uot;96%&uot; border=&uot;0&uot; align=&uot;center&uot; cellpadding=&uot;0&uot; cellspacing=&uot;10&uot; class=&uot;content&uot;>
图解把EXCEL数据导入到SQLServer

实验环境:W I N X P,M S O f f i c e E x c e l2007,S q l S e r v e r2008准备数据:Excel文档:D:\test\重复出修率.xlsx方法一:第一步:打开SSMS:开始→所有程序→MicrosoftSqlServer2008→SqlServerManagementStudio第二步:连接数据库:在’对象资源管理器’中点击连接→数据库引擎登陆服务器P.S:如果没有看到’对象资源管理器’,点击左上角的视图→对象管理器第三步:登陆成功后,右击你要导入数据的数据库名,我这里数据库名是’TEST’右击TEST→任务→导入数据这时候会出现一个向导:点击下一步在弹出的窗口中,数据源选择:MicrosoftExcel;Excel文件路径就选择你本地电脑存放Excel文档的路径,我这里是D:\test\重复出修率.xlsxExcel版本选择Excel2007可以根据你office的版本,选择其他如Excel2003等等;选中首行包含列名称框,最后点击下一步“首行包含列名称”是指Excel中的首行数据插入数据库后将作为新建表的列名.在弹出窗口中,目标可以采取默认的,服务器名称也是一样可以选择身份验证,最后选择你要插入数据到哪个数据库中;如我这里选的是’TEST’,选好后点击下一步如果就把Excel数据插入一个新表,就选择复制一个或多个表或视图的数据如果想把Excel数据插入到已存在的一张表中,则选择下面的编写查询以指定要传输的数据我这里是选择上面一个,然后点击下一步接着会弹出Excel表中的sheet表名字,如果你没有修改过sheet表名字,则可能显示的是’shee1$’,’shee2$’,’shee3$’等等.然后你选中你想要导入的哪张表的数据,我这里导入的是’aug$’选中后,右边的目标栏位中会出现内容,dbo是指数据库的架构名,aug$只是新建的表名,如果你想修改表明,双击就可以表明进入编辑状态就可以修改了;我这里修改的表名称为:aug_info修改后你也可以点击编辑映射你可以在这里修改目标,类型,是否可以为NULL,大小等建表数据;修改好后,点击确定,如果不想修改就点击取消返回上个窗口后,你也可以点击预览预览里面是Excel表中的一些数据;点击确定,然后点击下一步在弹出的页面中,就选中立即运行,至于保存SSIS包我也不是很清楚干嘛的;看样子好像是加密来着;然后点击下一步这个窗口就是一些提示信息,点击完成这个窗口是导入数据提示信息,看来我导入数据成功了;新建表名为aug_info,插入数据336行,所在数据库为TEST.点击关闭按钮就可以了;然后就是到SSMS中查看是否新生成了aug_info这张表.刷新TEST数据库或者重新登录SSMS在TEST数据库下,查看表,发现有个表名是aug_info进一步确认下,数据是否有误.点击对象资源管理器上面的新建查询,输入:use TESTselect COUNT as有多少行数据from aug_infoselectfrom aug_info前面显示‘已复制336行’,现在查询到表中有336行数据;看来这个表就是刚刚从Excel中导入的数据;OK,大功告成;很简单吧,点点鼠标就可以了P.S:前面到这里的时候,选择了上面的复制一个或多个表或视图的数据那下面的编写查询以指定要传输的数据怎么用呢下面我们来试一下,重新导入Excel,到这一步选择下面按钮,然后点击下一步发现这个是用来写SQL代码的;这个该怎么用呢我也没用过,百度了下;这个主要针对从数据库中导出条件筛选的数据.比如有一张test表,我只想导出表的其中一个字段或者几个字段的数据.就可以用这个.selectid,namefromtestwhere条件方法二:--首先打开SSMS,然后点击左上角的新建查询N,在右边弹出的窗口中输入一下代码:代码一:----------------------------------------------------------------------------------------useTEST---‘TEST’是数据库名字,你可以切换到你想要的数据库或直接输入数据库名字----根据系统需要使用这几段批处理命令打开相应功能EXECsp_configure'showadvancedoptions',1;GORECONFIGURE;GOEXECsp_configure'AdHocDistributedQueries',1;GORECONFIGURE;GO----以上为根据实际情况的可选命令----开始插入数据到TEST数据库的一个新表中selectintonewtable_namefromOpenDataSourceSource="c:\daoru.xlsx";Extendedproperties="Excel12.0;HDR=Yes"'... sheet1$goP.S:1:执行这段代码之前,你需要准备导入的数据;我用的是Excel2007,Excel文件的名字为“daoru”,放在C盘目录下;2:代码中的selectintonewtable_namefrom...这是把excel中的数据插入到TEST数据库中,并同时新建表名为newtable_name存放插入的数据.3:代码中的Office2007的数据库驱动为“”,如果是Office2003的话应改成“”,还有Office2007中Excel的“Extendedproperties”中为“Excel12.0”而Office2003为“Excel8.0”4:代码中'DataSource="c:\daoru.xlsx"就是要导入数据的文件存放路径.注意后缀:Excel2007的为.xlsx;Excel2003的为.xls5:代码中的...sheet1$为表名,格式为:XXX$或者XXX$,不需要中括号也行,而且表名不能以数字开头其实这是几乎所有编程语言的变量命名规则,切记没有修改过名字的话,Excel默认是shee1,shee2,shee3....6:当然,你也可以使导入的数据,不用新建表.而是直接导入到数据库已有的表中,只要稍微修改代码就可以了.代码二:---------------------------------------------------------------------------------------insertinto已存在的表名字段一,字段二selectA,BfromOpenDataSourceSource="c:\daoru.xlsx";Extendedproperties="Excel12.0;HDR=Yes"'... sheet1$go---------------------------------------------------------------------------------------代码二中,A,B表示的意思是Excel中的A列和B列,但是直接输入A,B是没有用的.这里还要提醒一点,导入数据的时候,系统默认Excel的第一行数据是字段名.所以,你可以把Excel的第一行的前两列数据改为A和B,这样就可以了如果Excel中的列数和数据库中的已存在的表的列数相等,也可以改成如下:代码三:---------------------------------------------------------------------------------------insertinto已存在的表名selectfromOpenDataSourceSource="c:\daoru.xlsx";Extendedproperties="Excel12.0;HDR=Yes"'... sheet1$go---------------------------------------------------------------------------------------。
asp向sql中导入excel

string tRealName, tSex, tInClass, tQuestion, tAnswer;
tRealName = ds.Tables["[Sheet1$]"].Rows[i]["姓名"].ToString().Trim();
public SqlConnection sqlcon; //创建SQL连接
public SqlCommand sqlcom; //创建SQL命令对象
public ExcelToSQL()
{
DataOperation dataOperation = new DataOperation(); //用到平台的函数,就是初始化SqlConnection对象
{
columnName += dt.Columns[i].ColumnName + ",";
string currentColumn = dt.Columns[i].ToString().ToUpper(); //当前列名
for (int j = 0; j < tableField.Count; j++)
using System.Data.SqlClient;
public class ExcelToSQL
{
//string SqlConnectionString = "Server=(local);Initial Catalog=Test;Integrated Security=True";
<html xmlns="/1999/xhtml">
<head runat="server">
如何将EXCEL中的数据直接导入 SQL SERVER 2000中的数据库

先读取EXCEL中的数据private void btnView_Click(object sender, System.EventArgs e){dgExcelData.DataSource = null;FileDialog dlgOpen = new OpenFileDialog();dlgOpen.Filter="Excel Files (*.xls)|*.xls";if(dlgOpen.ShowDialog() == DialogResult.OK){txtPath.Text=dlgOpen.FileName;string strCon = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "+txtPath.Text.Trim()+";Extended Properties=Excel 8.0" ; OleDbConnection myConn = new OleDbConnection();try{this.Cursor = Cursors.WaitCursor;//创建一个数据Excel连接****************************************************************** myConn = new OleDbConnection ( strCon ) ;string strCom = " SELECT * FROM [Sheet1$]" ;myConn.Open ();//打开连接得到数据集合oDS.Clear();OleDbDataAdapter myCommand = new OleDbDataAdapter( strCom , myConn ) ;myCommand.Fill ( oDS , "[Sheet1$]" ) ;//关闭连接myConn.Close ( ) ;if (!oDS.Tables[0].Columns.Contains("Insert Result"))oDS.Tables[0].Columns.Add("Insert Result");dgExcelData.SetDataBinding(oDS,"[Sheet1$]");btnOk.Enabled = true;this.Cursor = Cursors.Arrow;inifrom();}catch(Exception err1){MessageBox.Show(err1.Message);myConn.Close();this.Cursor = Cursors.Arrow;}}//END}sql中右键所有任务导入数据选择EXCEL版本即可下面是导出真正Excel文件的方法:if exists (select * from dbo.sysobjects where id = object_id(N '[dbo].[p_exporttb] ') and OBJECTPROPERTY(id, N'IsProcedure ') = 1)drop procedure [dbo].[p_exporttb]GO/*--数据导出EXCEL导出表中的数据到Excel,包含字段名,文件为真正的Excel文件,如果文件不存在,将自动创建文件,如果表不存在,将自动创建表基于通用性考虑,仅支持导出标准数据类型--邹建 2003.10(请保留此信息)--*//*--调用示例p_exporttb @tbname= '地区资料 ',@path= 'c:\ ',@fname= 'aa.xls ' --*/create proc p_exporttb@tbname sysname, --要导出的表名@path nvarchar(1000), --文件存放目录@fname nvarchar(250)= ' ' --文件名,默认为表名asdeclare @err int,@src nvarchar(255),@desc nvarchar(255),@out intdeclare @obj int,@constr nvarchar(1000),@sql varchar(8000),@f dlist varchar(8000)--参数检测if isnull(@fname, ' ')= ' ' set @fname=@tbname+ '.xls '--检查文件是否已经存在if right(@path,1) <> '\ ' set @path=@path+ '\ 'create table #tb(a bit,b bit,c bit)set @sql=@path+@fnameinsert into #tb exec master..xp_fileexist @sql--数据库创建语句set @sql=@path+@fnameif exists(select 1 from #tb where a=1)set @constr= 'DRIVER={Microsoft Excel Driver (*.xls)};DSN= ' ' ' ';READONLY=FALSE '+ ';CREATE_DB= " '+@sql+ ' ";DBQ= '+@sqlelseset @constr='Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties="Excel 8.0;HDR=YES '+ ';DATABASE= '+@sql+ ' " '--连接数据库exec @err=sp_oacreate 'adodb.connection ',@obj outif @err <> 0 goto lberrexec @err=sp_oamethod @obj, 'open ',null,@constrif @err <> 0 goto lberr/*--如果覆盖已经存在的表,就加上下面的语句--创建之前先删除表/如果存在的话select @sql= 'drop table [ '+@tbname+ '] 'exec @err=sp_oamethod @obj, 'execute ',@out out,@sql--*/--创建表的SQLselect @sql= ' ',@fdlist= ' 'select @fdlist=@fdlist+ ',[ '++ '] ',@sql=@sql+ ',[ '++ '] '+casewhen like '%char 'then case when a.length> 255 then 'memo 'else 'text( '+cast(a.length as varchar)+ ') ' endwhen like '%int ' or = 'bit' then 'int 'when like '%datetime ' then 'datetime 'when like '%money ' then 'money 'when like '%text ' then 'memo 'else endFROM syscolumns a left join systypes b on a.xtype=b.x usertypewhere not in( 'image ', 'uniqueidentifier ', 'sql_variant ', 'varbinary ', 'binary ', 'timestamp ')and object_id(@tbname)=idselect @sql= 'create table [ '+@tbname+ ']( '+substring(@sql,2,8000)+ ') ',@fdlist=substring(@fdlist,2,8000)exec @err=sp_oamethod @obj, 'execute ',@out out,@sqlif @err <> 0 goto lberrexec @err=sp_oadestroy @obj--导入数据set @sql= 'openrowset( ' 'MICROSOFT.JET.OLEDB.4.0 ' ', ''Excel 8.0;HDR=YES;IMEX=1;DATABASE= '+@path+@fname+ ' ' ',[ '+@tbname+ '$]) 'exec( 'insert into '+@sql+ '( '+@fdlist+ ') select '+@fdlist+ ' from '+@tbname)returnlberr:exec sp_oageterrorinfo 0,@src out,@desc outlbexit:select cast(@err as varbinary(4)) as 错误号,@src as 错误源,@desc as 错误描述select @sql,@constr,@fdlistgoif exists (select * from dbo.sysobjects where id = object_id(N '[dbo].[p_exporttb] ') and OBJECTPROPERTY(id, N'IsProcedure ') = 1)drop procedure [dbo].[p_exporttb]GO/*--数据导出EXCEL导出查询中的数据到Excel,包含字段名,文件为真正的Excel文件如果文件不存在,将自动创建文件如果表不存在,将自动创建表基于通用性考虑,仅支持导出标准数据类型--邹建 2003.10(请保留此信息)--*//*--调用示例p_exporttb @sqlstr= 'select * from 地区资料 ',@path= 'c:\ ',@fname= 'aa.xls ',@sheetname= '地区资料 '--*/create proc p_exporttb@sqlstr varchar(8000), --查询语句,如果查询语句中使用了order by ,请加上top 100 percent@path nvarchar(1000), --文件存放目录@fname nvarchar(250), --文件名@sheetname varchar(250)= ' ' --要创建的工作表名,默认为文件名asdeclare @err int,@src nvarchar(255),@desc nvarchar(255),@out intdeclare @obj int,@constr nvarchar(1000),@sql varchar(8000),@f dlist varchar(8000)--参数检测if isnull(@fname, ' ')= ' ' set @fname= 'temp.xls 'if isnull(@sheetname, ' ')= ' ' set @sheetname=replace(@fname, '. ', '# ')--检查文件是否已经存在if right(@path,1) <> '\ ' set @path=@path+ '\ 'create table #tb(a bit,b bit,c bit)set @sql=@path+@fnameinsert into #tb exec master..xp_fileexist @sql--数据库创建语句set @sql=@path+@fnameif exists(select 1 from #tb where a=1)set @constr= 'DRIVER={Microsoft Excel Driver (*.xls)};DSN= ' ' ' ';READONLY=FALSE '+ ';CREATE_DB= " '+@sql+ ' ";DBQ= '+@sqlelseset @constr='Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties="Excel 8.0;HDR=YES '+ ';DATABASE= '+@sql+ ' " '--连接数据库exec @err=sp_oacreate 'adodb.connection ',@obj outif @err <> 0 goto lberrexec @err=sp_oamethod @obj, 'open ',null,@constrif @err <> 0 goto lberr--创建表的SQLdeclare @tbname sysnameset @tbname= '##tmp_ '+convert(varchar(38),newid())set @sql= 'select * into [ '+@tbname+ '] from( '+@sqlstr+ ') a 'exec(@sql)select @sql= ' ',@fdlist= ' 'select @fdlist=@fdlist+ ',[ '++ '] ',@sql=@sql+ ',[ '++ '] '+casewhen like '%char 'then case when a.length> 255 then 'memo 'else 'text( '+cast(a.length as varchar)+ ') ' endwhen like '%int ' or = 'bit' then 'int 'when like '%datetime ' then 'datetime 'when like '%money ' then 'money 'when like '%text ' then 'memo 'else endFROM tempdb..syscolumns a left join tempdb..systypes b on a.xtype=b.xusertypewhere not in( 'image ', 'uniqueidentifier ', 'sql_variant ', 'varbinary ', 'binary ', 'timestamp ')and a.id=(select id from tempdb..sysobjects where name=@ tbname)if @@rowcount=0 returnselect @sql= 'create table [ '+@sheetname+ ']( '+substring(@sql,2,8000)+ ') ',@fdlist=substring(@fdlist,2,8000)exec @err=sp_oamethod @obj, 'execute ',@out out,@sqlif @err <> 0 goto lberrexec @err=sp_oadestroy @obj--导入数据set @sql= 'openrowset( ' 'MICROSOFT.JET.OLEDB.4.0 ' ', ''Excel 8.0;HDR=YES;DATABASE= '+@path+@fname+ ' ' ',[ '+@sheetname+ '$]) 'exec( 'insert into '+@sql+ '( '+@fdlist+ ') select '+@fdlist+ ' from [ '+@tbname+ '] ')set @sql= 'drop table [ '+@tbname+ '] 'exec(@sql)returnlberr:exec sp_oageterrorinfo 0,@src out,@desc outlbexit:select cast(@err as varbinary(4)) as 错误号,@src as 错误源,@desc as 错误描述select @sql,@constr,@fdlistgo。
asp导航excel数据到mssqlaccessmysql等数据方法

asp导航excel数据到mssqlaccessmysql等数据方法下面是一段简单的由asp导入excel数据保存到其它的数据如有mssql access mysql 等哦好了费话不说多了来看看下面的代码吧<! #include file="adoconn asp" > <% Set xlsconn = server CreateObject("adodb connection") set rs=server CreateObject("adodb recordset")source =server mappath(" ")&""&replace(request("path") "/" "") myConn_Xsl="Provider=Microsoft Jet OLEDB ;Data Source=" &source & ";Extended Properties=Excel " xlsconn open myConn_Xslsql="select * from [商品列表$]" set rs=xlsconn execute(sql) if not rs eof then while not rs eof names=rs("商品名") pic=rs("图片")sql="insert into [product](namese pic) values( "& names &" "& pic &" )" conn execute(sql)rs movenext wendend if response write "导入成功" end if %>数据连接文件<! #include file="adoconn asp" >lishixinzhi/Article/program/net/201311/14100。
把Excel表导入SQL数据库的两种方法

把Excel表导入SQL数据库的两种方法SQLServer自身就有导入功能的1、打开企业管理器,打开要导入数据的数据库,在表上按右键,所有任务-->导入数据,弹出DTS导入/导出向导,按下一步,2、选择数据源 Microsoft Excel 97-2000,文件名选择要导入的xls文件,按下一步,3、选择目的用于SQL Server 的Microsoft OLE DB提供程序,服务器选择本地(如果是本地数据库的话,如 VVV),使用SQL Server身份验证,用户名sa,密码为空,数据库选择要导入数据的数据库(如 client),按下一步,4、选择用一条查询指定要传输的数据,按下一步,5、按查询生成器,在源表列表中,有要导入的xls文件的列,将各列加入到右边的选中的列列表中,这一步一定要注意,加入列的顺序一定要与数据库中字段定义的顺序相同,否则将会出错,按下一步,6、选择要对数据进行排列的顺序,在这一步中选择的列就是在查询语句中 order by 后面所跟的列,按下一步,7、如果要全部导入,则选择全部行,按下一步,8、则会看到根据前面的操作生成的查询语句,确认无误后,按下一步,9、会看到表/工作表/Excel命名区域列表,在目的列,选择要导入数据的那个表,按下一步,10、选择立即运行,按下一步,11、会看到整个操作的摘要,按完成即可。
将EXCEL的数据提出放在数据集中,在通过循环将从表插入<%'On Error Resume Next'导入Excel电子表格数据到SQL Sever数据库Open_Conn(SqlDatabaseName,SqlPassword,SqlUsername,SqlLocalName,SqlConn)'创建数据库连接对象并打开数据库连接Dim ConnStr'SQL Server数据库连接参数:数据库名、用户密码、用户名、连接名(本地用local,外地用IP)ConnStr = "Provider=Sqloledb; User ID=" & SqlUsername & "; Password=" & SqlPassword & "; Initial Catalog = " & SqlDatabaseName & "; Data Source=" & SqlLocalName & ";"Set SqlConn = Server.CreateObject("ADODB.Connection")SqlConn.Open ConnStrIf Err ThenErr.ClearSet SqlConn = NothingResponse.Write "数据连接错误!"Response.EndEnd IfEndClose_Conn(SqlConn)'关闭数据库连接并清除数据库连接对象If IsObject(SqlConn) ThenSqlConn.CloseSet SqlConn = NothingEnd IfEndCall Open_Conn("Shat_EDG","","sa","(local)",SqlConn) '打开本地SQL Server数据库连接Call Open_Conn("Shat_EDG","","sa","ssh03",SqlConn1) '打开远程SQLServer数据库连接Get_EMP_CnName(NTACCNT)'根据用户NT帐号得到用户中文名Dim Sql1,Rs1Sql1 = "Select EMP_CNAME From RF_EMPLOYEE Where EMP_NTACCNT='"&NTACCNT&"'"Set Rs1 = Server.CreateObject("Adodb.RecordSet")Rs1.Open Sql1,SqlConn1,1,1If Rs1.Eof ThenGet_EMP_CnName = ""ElseGet_EMP_CnName = Rs1("EMP_CNAME")End IfRs1.CloseSet Rs1 = NothingEnd %><html><head><title>导入Excel电子表格数据到SQL Sever数据库</title><body bgcolor="#ACD9AF"><center><b>导入Excel电子表格数据到SQL Sever数据库</b></center><FORM METHOD="POST" name="form1">请选择数据源(本地库):<SELECT NAME="Table" title="请选择需要导入数据的表"><option></option><% Dim RsSqlDatabaseTableSet RsSqlDatabaseTable = SqlConn.OpenSchema(20)Do While Not RsSqlDatabaseTable.Eof %><option<%If Trim(Request("Table"))=RsSqlDatabaseTable(2) Then Response.Write " selected"%>><%=RsSqlDatabaseTable(2)%></option> <% RsSqlDatabaseTable.MoveNext:LoopSet RsSqlDatabaseTable = Nothing %></SELECT><input type=submit name=submit ="开始导出"><br>请选择目标表(远程库):<SELECT NAME="Table1" title="请选择需要导入数据的表"><option></option><% Dim RsSqlDatabaseTable1Set RsSqlDatabaseTable1 = SqlConn1.OpenSchema(20)Do While Not RsSqlDatabaseTable1.Eof %><option<%If Trim(Request("Table1"))=RsSqlDatabaseTable1(2) Then Response.Write " selected"%>><%=RsSqlDatabaseTable1(2)%></option> <% RsSqlDatabaseTable1.MoveNext:LoopSet RsSqlDatabaseTable1 = Nothing %></SELECT></FORM><font color=blue>导出过程中请不要刷新页面!</font><br><%If Trim(Request("Table1")) <> "" ThenDim Sql,RsSql = "Select * From Sheet1$" 'Sheet1$是我们实现用SQL Server自身数据转换功能得到的表名Set Rs = SqlConn.Execute(Sql)If Rs.Eof And Rs.Bof ThenResponse.write "没有找到您需要的数据!!<br>"ElseDo While Not Rs.EofSqlInsert = "Insert Into "&Trim(Request("Table1"))&"(EDG_Project_Name,EDG_Project_No,EDG_Project_VM,EDG_Project_VM_CnName ,EDG_Project_M,EDG_Project_M_CnName,EDG_Project_Director,EDG_Project_ Director_CnName) s ('"&Trim(Rs("工程名称"))&"','"&Trim(Rs("工程编号"))&"','"&Trim(Rs("项目副理"))&"','"&Trim(Rs("项目副理"))&" ("&Get_EMP_CnName(Trim(Rs("项目副理")))&")"&"','"&Trim(Rs("项目经理"))&"','"&Trim(Rs("项目经理"))&" ("&Get_EMP_CnName(Trim(Rs("项目经理")))&")"&"','"&Trim(Rs("项目总监"))&"','"&Trim(Rs("项目总监"))&" ("&Get_EMP_CnName(Trim(Rs("项目总监")))&")"&"')"' Response.Write SqlInsert'此处插入的值根据实际数据库结构进行调整SqlConn1.Execute(SqlInsert)'插入Excel表格裏所有东东Rs.MoveNextLoopResponse.Write "<font color=red>恭喜,成功导出数据!^_^</font><br>" End IfRs.CloseSet Rs = NothingEnd IfCall Close_Conn(SqlConn) '关闭Excel数据库连接Call Close_Conn(SqlConn1) '关闭SQL Server数据库连接 %>。
Execle数据批量导入sqlserver数据库

.net调用存储过程详解小眼睛老鼠本文的数据库用的是sql server自带数据Northwind连接字符串string conn = ConfigurationManager.ConnectionStrings["NorthwindConnectio nString"].ConnectionString;confige文件<connectionStrings><add name="NorthwindConnectionString" connectionString="Data Sourc e=.;Initial Catalog=Northwind;Integrated Security=True" providerName="Syste m.Data.SqlClient"/></connectionStrings>1. 只返回单一记录集的存储过程SqlConnection sqlconn = new SqlConnection(conn);SqlCommand cmd = new SqlCommand();// 设置sql连接cmd.Connection = sqlconn;// 如果执行语句mandText = "Categoriestest1";// 指定执行语句为存储过程mandType = CommandType.StoredProcedure; SqlDataAdapter dp = new SqlDataAdapter(cmd);DataSet ds = new DataSet();// 填充datasetdp.Fill(ds);// 以下是显示效果GridView1.DataSource = ds;GridView1.DataBind();存储过程Categoriestest1CREATE PROCEDURE Categoriestest1ASselect *from CategoriesGO2. 没有输入输出的存储过程c#代码部分SqlConnection sqlconn = new SqlConnection(conn);SqlCommand cmd = new SqlCommand();cmd.Connection = sqlconn;mandText = "Categoriestest2";mandType = CommandType.StoredProcedure; sqlconn.Open();// 执行并显示影响行数Label1.Text = cmd.ExecuteNonQuery().ToString();sqlconn.Close();存储过程Categoriestest2CREATE PROCEDURE Categoriestest2 ASinsert into dbo.Categories(CategoryName,[Description],[Picture])values ('test1','test1',null)GO3. 有返回值的存储过程c#代码部分SqlConnection sqlconn = new SqlConnection(conn);SqlCommand cmd = new SqlCommand();cmd.Connection = sqlconn;mandText = "Categoriestest3";mandType = CommandType.StoredProcedure;// 创建参数IDataParameter[] parameters = {new SqlParameter("rval", SqlDbType.Int,4)};// 将参数类型设置为返回值类型parameters[0].Direction = ParameterDirection.ReturnValue;// 添加参数cmd.Parameters.Add(parameters[0]);sqlconn.Open();// 执行存储过程并返回影响的行数Label1.Text = cmd.ExecuteNonQuery().ToString();sqlconn.Close();// 显示影响的行数和返回值Label1.Text += "-" + parameters[0].Value.ToString() ;存储过程Categoriestest3CREATE PROCEDURE Categoriestest3ASinsert into dbo.Categories(CategoryName,[Description],[Picture])values ('test1','test1',null)return @@rowcountGO4. 有输入参数和输出参数的存储过程c#代码部分SqlConnection sqlconn = new SqlConnection(conn);SqlCommand cmd = new SqlCommand();cmd.Connection = sqlconn;mandText = "Categoriestest4";mandType = CommandType.StoredProcedure;// 创建参数IDataParameter[] parameters = {new SqlParameter("@Id", SqlDbType.Int,4) ,new SqlParameter("@CategoryName", SqlDbType.NVarChar,15) , };// 设置参数类型parameters[0].Direction = ParameterDirection.Output; // 设置为输出参数 parameters[1].Value = "testCategoryName";// 添加参数cmd.Parameters.Add(parameters[0]);cmd.Parameters.Add(parameters[1]);sqlconn.Open();// 执行存储过程并返回影响的行数Label1.Text = cmd.ExecuteNonQuery().ToString();sqlconn.Close();// 显示影响的行数和输出参数Label1.Text += "-" + parameters[0].Value.ToString() ;存储过程Categoriestest4CREATE PROCEDURE Categoriestest4@id int output,@CategoryName nvarchar(15)ASinsert into dbo.Categories(CategoryName,[Description],[Picture])values (@CategoryName,'test1',null)set @id = @@IDENTITYGO5. 同时具有返回值、输入参数、输出参数的存储过程c#代码部分SqlConnection sqlconn = new SqlConnection(conn);SqlCommand cmd = new SqlCommand();cmd.Connection = sqlconn;mandText = "Categoriestest5";mandType = CommandType.StoredProcedure;// 创建参数IDataParameter[] parameters = {new SqlParameter("@Id", SqlDbType.Int,4) ,new SqlParameter("@CategoryName", SqlDbType.NVarChar,15) ,new SqlParameter("rval", SqlDbType.Int,4)};// 设置参数类型parameters[0].Direction = ParameterDirection.Output; // 设置为输出参数parameters[1].Value = "testCategoryName"; // 给输入参数赋值 parameters[2].Direction = ParameterDirection.ReturnValue; // 设置为返回值// 添加参数cmd.Parameters.Add(parameters[0]);cmd.Parameters.Add(parameters[1]);cmd.Parameters.Add(parameters[2]);sqlconn.Open();// 执行存储过程并返回影响的行数Label1.Text = cmd.ExecuteNonQuery().ToString();sqlconn.Close();// 显示影响的行数,输出参数和返回值Label1.Text += "-" + parameters[0].Value.ToString() + "-" + parameters[2] .Value.ToString();存储过程Categoriestest5CREATE PROCEDURE Categoriestest5@id int output,@CategoryName nvarchar(15)ASinsert into dbo.Categories(CategoryName,[Description],[Picture])values (@CategoryName,'test1',null)set @id = @@IDENTITYreturn @@rowcountGO6. 同时返回参数和记录集的存储过程c#代码部分SqlConnection sqlconn = new SqlConnection(conn);SqlCommand cmd = new SqlCommand();cmd.Connection = sqlconn;mandText = "Categoriestest6";mandType = CommandType.StoredProcedure;// 创建参数IDataParameter[] parameters = {new SqlParameter("@Id", SqlDbType.Int,4) ,new SqlParameter("@CategoryName", SqlDbType.NVarChar,15) ,new SqlParameter("rval", SqlDbType.Int,4) // 返回值};// 设置参数类型parameters[0].Direction = ParameterDirection.Output; // 设置为输出参数parameters[1].Value = "testCategoryName"; // 给输入参数赋值parameters[2].Direction = ParameterDirection.ReturnValue; // 设置为返回值// 添加参数cmd.Parameters.Add(parameters[0]);cmd.Parameters.Add(parameters[1]);cmd.Parameters.Add(parameters[2]);SqlDataAdapter dp = new SqlDataAdapter(cmd);DataSet ds = new DataSet();// 填充datasetdp.Fill(ds);// 显示结果集GridView1.DataSource = ds.Tables[0];GridView1.DataBind();Label1.Text = "";// 显示输出参数和返回值Label1.Text += parameters[0].Value.ToString() + "-" + parameters[2].Val ue.ToString();存储过程Categoriestest6CREATE PROCEDURE Categoriestest6@id int output,@CategoryName nvarchar(15)ASinsert into dbo.Categories(CategoryName,[Description],[Picture])values (@CategoryName,'test1',null)set @id = @@IDENTITYselect * from Categoriesreturn @@rowcountGO7. 返回多个记录集的存储过程c#代码部分SqlConnection sqlconn = new SqlConnection(conn);SqlCommand cmd = new SqlCommand();cmd.Connection = sqlconn;mandText = "Categoriestest7";mandType = CommandType.StoredProcedure; SqlDataAdapter dp = new SqlDataAdapter(cmd);DataSet ds = new DataSet();// 填充datasetdp.Fill(ds);// 显示结果集1GridView1.DataSource = ds.Tables[0];GridView1.DataBind();// 显示结果集2GridView2.DataSource = ds.Tables[1];GridView2.DataBind();存储过程Categoriestest7CREATE PROCEDURE Categoriestest7ASselect * from Categoriesselect * from Categories GO。
ExcelVBA导入Excel中数据到SQLServer中

[方法一]如何把EXCEL中的数据导入SQL SERVER数据库中(2010-12-30 17:16:53)有时候需要把E XCEL中的数据导入到数据库中。
一条一条的在数据库中建数据显然不可取,如何找一条快捷的途径进行转换是很有必要的。
在这里主要是介绍一种在EX CEL中用V BA进行编程,把EXCEL的数据转换成S QL语句,存入到一个文件中,然后在数据库服务器上提交这些SQL语句来实现。
一、两边的数据格式(一)数据库的表结构生成数据库表的SQL语句如下:createtable Address(ID Integer identit y(1,1) not null primary key,Name varchar(20) not null,Dept varchar(50),Spell varchar(20),Mobile varchar(11),Tel varchar(20),EMail varchar(30),VOIP varchar(6),Remark varchar(200),);EXCEL中的数据格式(二)转换的VBA函数Sub Generat eSQL()Dim i, k As LongDim s As StringOpen "d:\txl.sql" For OutputAs #1 '打开一个文件以供输入SQL语句i = 2While Cells(i, 1) <> ""s = "INSERTINTO ADDRESS (Name,Dept,Mobile,Tel,VOIP,EMail) VALUES("For k = 1 To 5s = s & "'" & Cells(i, k) & "',"Nexts = s & "'" & Cells(i, 6) & "');"Print #1, s '输出一条语句至文件i = i + 1WendClose #1 '关闭文件End Sub以上的代码用于逐行把数据转换成SQL语句写入“d:\txl.sql”中。
SQLServer数据库中批量导入数据的四种方法

SQLServer数据库中批量导入数据的四种方法在软件项目实施的时候,数据导入一直是项目人员比较头疼的问题。
其实,在SQL Server中集成了很多成批导入数据的方法。
有些项目实施顾问头疼的问题,在我们数据库管理员眼中,是小菜一碟。
现在的重点就是,如何让用户了解这些方法,让数据导入变得轻松一些。
第一:使用Select Into语句若企业数据库都采用的是SQL Server数据库的话,则可以利用Select Into语句来实现数据的导入。
Select Into语句,他的作用就是把数据从另外一个数据库中查询出来,然后加入到某个用户指定的表中。
在使用这条语句的时候,需要注意几个方面的内容。
一、是需要在目的数据库中先建立相关的表。
如想把进销存系统数据库(SQLServer)中的产品信息表(Product)导入到ERP系统中的产品信息表(M_Product)中。
则前期是在ERP系统的数据库中已经建立了这张产品信息表。
二、是这种方法只复制表中的数据,而不复制表中的索引。
如在进销存系统数据中的产品信息表中,在产品编号、产品种类等字段上建立了索引。
则利用Select Into语句把数据复制到ERP系统的表中的时候,只是复制了数据内容的本身,而不会复制索引等信息。
三、是这条语句使用具有局限性。
一般情况下,这只能够在SQL Server数据库中采用。
不过,对于SQL Server不同版本的数据库,如2008或者2003,还都是兼容的。
若需要导入的对象数据库不是SQL Server的,则需要采用其他的方法。
四、是采用这条语句的话,在目的表中必须不存在数据。
否则的话,目的表中的数据会被清除。
也就是说,这个语句不支持表与表数据的合并。
在SQL Server中,有一条类似的语句,可以实现这个功能。
这条语句就是:Insert Into。
他的作用就是把另外一张表中的数据插入到当前表中。
若用户想要的时表与表数据的合并,则可以采用这条语句。
ASP将Excel数据导入到SQLServer的实现代码

ASP将Excel数据导⼊到SQLServer的实现代码复制代码代码如下:<form action="insert.asp" method="post" enctype="multipart/form-data" name="form1" onSubmit="b1_onclick()"> <table width="500" border="1" align="center" cellpadding="0" cellspacing="0"><tr><td colspan="2" bgcolor="#999999" class="t">选择⽂件</td></tr><tr><td colspan="2" class="t"> </td></tr><tr><td width="126" class="t">选择⽂件(excel)</td><td width="368" class="t"><label><input name="filexls" type="file" size="35"></label></td></tr><tr><td colspan="2" class="t"><label><input type="submit" name="Submit" value="导⼊数据"></label><a href="1122.asp" class="t">返回</a></td></tr></table></form><!--#include virtual="/inc/clsdbctrl.asp"--><!--#include virtual="/inc/function.asp"--><%dim upfile_5xSoft_StreamClass upload_5xSoftdim Form,File,VersionPrivate Sub Class_Initializedim iStart,iFileNameStart,iFileNameEnd,iEnd,vbEnter,iFormStart,iFormEnd,theFiledim strDiv,mFormName,mFormValue,mFileName,mFileSize,mFilePath,iDivLen,mStrVersion="任翔专⽤上传程序"if Request.TotalBytes<1 then Exit Subset Form=CreateObject("Scripting.Dictionary")set File=CreateObject("Scripting.Dictionary")set upfile_5xSoft_Stream=CreateObject("Adodb.Stream")upfile_5xSoft_Stream.mode=3upfile_5xSoft_Stream.type=1upfile_5xSoft_Stream.openupfile_5xSoft_Stream.write Request.BinaryRead(Request.TotalBytes)vbEnter=Chr(13)&Chr(10)iDivLen=inString(1,vbEnter)+1strDiv=subString(1,iDivLen)iFormStart=iDivLeniFormEnd=inString(iformStart,strDiv)-1while iFormStart < iFormEndiStart=inString(iFormStart,"name=""")iEnd=inString(iStart+6,"""")mFormName=subString(iStart+6,iEnd-iStart-6)iFileNameStart=inString(iEnd+1,"filename=""")if iFileNameStart>0 and iFileNameStart<iFormEnd theniFileNameEnd=inString(iFileNameStart+10,"""")iStart=inString(iFileNameEnd+1,vbEnter&vbEnter)iEnd=inString(iStart+4,vbEnter&strDiv)if iEnd>iStart thenmFileSize=iEnd-iStart-4elsemFileSize=0end ifset theFile=new FileInfotheFile.FileName=getFileName(mFileName)theFile.FilePath=getFilePath(mFileName)theFile.FileSize=mFileSizetheFile.FileStart=iStart+4theFile.FormName=FormNamefile.add mFormName,theFileelseiStart=inString(iEnd+1,vbEnter&vbEnter)iEnd=inString(iStart+4,vbEnter&strDiv)if iEnd>iStart thenmFormValue=subString(iStart+4,iEnd-iStart-4)elsemFormValue=""end ifform.Add mFormName,mFormValueend ifiFormStart=iformEnd+iDivLeniFormEnd=inString(iformStart,strDiv)-1wendEnd SubPrivate Function subString(theStart,theLen)dim i,c,stempupfile_5xSoft_Stream.Position=theStart-1stemp=""for i=1 to theLenif upfile_5xSoft_Stream.EOS then Exit forc=ascB(upfile_5xSoft_Stream.Read(1))If c > 127 Thenif upfile_5xSoft_Stream.EOS then Exit forstemp=stemp&Chr(AscW(ChrB(AscB(upfile_5xSoft_Stream.Read(1)))&ChrB(c))) i=i+1elsestemp=stemp&Chr(c)End IfNextsubString=stempEnd functionPrivate Function inString(theStart,varStr)dim i,j,bt,theLen,strInString=0Str=toByte(varStr)theLen=LenB(Str)for i=theStart to upfile_5xSoft_Stream.Size-theLenif i>upfile_5xSoft_Stream.size then exit Functionupfile_5xSoft_Stream.Position=i-1if AscB(upfile_5xSoft_Stream.Read(1))=AscB(midB(Str,1)) thenInString=ifor j=2 to theLenif upfile_5xSoft_Stream.EOS theninString=0Exit forend ifif AscB(upfile_5xSoft_Stream.Read(1))<>AscB(MidB(Str,j,1)) thennextif InString<>0 then Exit Functionend ifnextEnd FunctionPrivate Sub Class_Terminateform.RemoveAllfile.RemoveAllset form=nothingset file=nothingupfile_5xSoft_Stream.closeset upfile_5xSoft_Stream=nothingEnd SubPrivate function GetFilePath(FullPath)If FullPath <> "" ThenGetFilePath = left(FullPath,InStrRev(FullPath, "\"))ElseGetFilePath = ""End IfEnd functionPrivate function GetFileName(FullPath)If FullPath <> "" ThenGetFileName = mid(FullPath,InStrRev(FullPath, "\")+1)ElseGetFileName = ""End IfEnd functionPrivate function toByte(Str)dim i,iCode,c,iLow,iHightoByte=""For i=1 To Len(Str)c=mid(Str,i,1)iCode =Asc(c)If iCode<0 Then iCode = iCode + 65535If iCode>255 TheniLow = Left(Hex(Asc(c)),2)iHigh =Right(Hex(Asc(c)),2)toByte = toByte & chrB("&H"&iLow) & chrB("&H"&iHigh)ElsetoByte = toByte & chrB(AscB(c))End IfNextEnd functionEnd ClassClass FileInfodim FormName,FileName,FilePath,FileSize,FileStartPrivate Sub Class_InitializeFileName = ""FilePath = ""FileSize = 0FileStart= 0FormName = ""End SubPublic function SaveAs(FullPath)dim dr,ErrorChar,iSaveAs=1if trim(fullpath)="" or FileSize=0 or FileStart=0 or FileName="" then exit function if FileStart=0 or right(fullpath,1)="/" then exit functionset dr=CreateObject("Adodb.Stream")upfile_5xSoft_Stream.position=FileStart-1upfile_5xSoft_Stream.copyto dr,FileSizedr.SaveToFile FullPath,2dr.Closeset dr=nothingSaveAs=0end functionEnd Class%><%function sqlstr(data)if not isnull(data) thensqlstr="'"& replace(data,"'","''") &"'"elsesqlstr="'"& data &"'"end ifend function%><%session.CodePage=936Server.ScriptTimeOut=600000set upload=new upload_5xsoftset file=upload.file("filexls")%><%if file.fileSize>0 thenfilename=year(now)&month(now)&day(now)&hour(now)&minute(now)&second(now)filename=filename+"."filenameend=file.filenamefilenameshow=file.filenamefilenameend=split(filenameend,".")if filenameend(1)="xls" thenfilename=filename&filenameend(1)file.saveAs Server.mappath("uploadfiles/"&filename)elseresponse.write "数据格式不对!"response.write "<a href=file_upload.asp>返回"response.end()end ifset file=nothingelseresponse.write "⽂件不能为空!"response.write "<a href=file_upload.asp>返回"response.end()End ifset upload=nothing'上传XLS⽂件结束,下⾯从上传的XLS⽂件中读取数据写⼊到SQL数据库strAddr=server.MapPath("uploadfiles/"&filename)set excelconn=server.createobject("adodb.connection")excelconn.open "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "+strAddr+";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'"set rs=server.CreateObject("adodb.recordset")set rs1=server.CreateObject("adodb.recordset")sql="select * from [Sheet1$]"rs.open sql,excelconn,1,3if not(rs.bof and rs.eof) thenrs.movenextdo while not rs.eof'response.Write(rs(1))sql1="select * from member"rs1.open sql1,conn,1,3rs1.addnewRandomizeusername=""Do While Len(username)<8 '随机密码位数num1=CStr(Chr((57-48)*rnd+48)) '0~9'num2=CStr(Chr((90-65)*rnd+65)) 'A~Znum3=CStr(Chr((122-97)*rnd+97)) 'a~zusername=username&num1&num3looprs1("username")=usernamers1("password")="bb0391ec1d7bda99"'bamboo123456 if rs(0)<>"" thenrs1("company")=rs(0)end ifif rs(1)<>"" thenrs1("realname")=rs(1)end ifif rs(2)<>"" thenrs1("sex")=sexn(rs(2))end ifif rs(3)<>"" thenrs1("prof")=rs(3)end ifif rs(4)<>"" thenrs1("tel")=rs(4)end ifif rs(5)<>"" thenrs1("mobile")=rs(5)end ifif rs(6)<>"" thenrs1("address")=rs(6)end ifif rs(7)<>"" thenrs1("area")=getclassdname(rs(7),"area","cn")end ifif rs(8)<>"" thenrs1("city")=getclassdname(rs(8),"area","cn")end ifif rs(9)<>"" thenrs1("fax")=rs(9)end ifif rs(10)<>"" thenrs1("comtype")=comtypem(rs(10))end ifif rs(11)<>"" thenrs1("operation")=rs(11)end ifrs1("passed")=1rs1("activated")=1rs1("lastlogintime")=now()rs1.updaters1.closers.movenextloopend ifrs.close()set rs=nothingset rs1=nothingexcelconn.Close()conn.close()set conn=nothingfunction sexn(str)select case strcase "男"sexn=0case "⼥"sexn=1end selectend functionfunction comtypem(str)select case strcase "⽵制品"comtypem=0case "⽵机械"comtypem=1end selectend functionfunction getclassdname(str,tablename,lang)If Not IsNumeric(id) Then Exit Functionset rs2=conn.execute ("select top 1 id from "& tablename &" where classname like '%"&str&"%'")if not rs2.eof ThenIf lang<>"" ThenIf lang="cn" Thengetclassdname=getclassdname & rs2(0)ElseIf lang="en" Thengetclassdname=getclassdname & rs2(0)End IfEnd Ifelsegetclassdname=0end ifrs2.closeEnd Function%><table width="300" border="1" align="center" cellpadding="0" cellspacing="0" bordercolor="#CCCCCC"> <tr><th bordercolor="#F1F3F8" bgcolor="#999999" class="t" scope="row"> </th></tr><tr><th class="t" scope="row">⽂件<% response.write (filenameshow) %>导⼊成功!</th></tr><tr><th class="t" scope="row"><a href="javascript:self.close()" class="t">关闭窗⼝</a></th></tr><tr><th class="t" scope="row"><a href="1122.asp" class="t">返回</a></th></tr></table>。
EXCEL批量导入到Sqlserver数据库并进行两表间数据的批量修改

EXCEL批量导⼊到Sqlserver数据库并进⾏两表间数据的批量修
改
Excel ⼤量数据导⼊到sqlserver⽣成临时表并将临时表某字段的数据批量更新的原表中的某个字段
1:⾸先要对EXCEL进⾏处理
列名改成英⽂,不要有多余的列和⾏(通过ctrl+shift 左或右隐藏⾏和列)
2.sqlserver界⾯选择数据库进⾏导⼊
3.数据源选择EXCEL 版本我选97-2003
4.选择需要导⼊的数据库
4.选择要导⼊的sheet,可预览或查看字段,如果Excel实现格式错误会报错
5.点下⼀步和完成就顺利导⼊了
接下来看下临时表⾥数据是否正确,有多余的空数据可以删掉
开始批量修改
附上Sql
把资产表⾥的两个⽇期字段的值都改为临时表⾥的数据,通过code字段关联资产表和临时表,最终实现批量修改
SELECT a.listingdate,a.obtaindate,b.RLinstenDate,b.Robtaindate,* FROM tab_assets as a join dbo.[核对⽇期导⼊⽤$] as b on a.code=b.code where b.bldate=0 or b.bodate=0
update tab_assets set tab_assets.obtaindate=dbo.[核对⽇期导⼊⽤$].RObtainDate,tab_assets.listingdate=dbo.[核对⽇期导⼊⽤$].RLinstenDate from dbo.[核对⽇期导⼊⽤$] join tab_assets on tab_assets.code=dbo.[核对⽇期导⼊⽤$].code。
将Excel文件数据导入到SqlServer数据库的三种方案

将Excel⽂件数据导⼊到SqlServer数据库的三种⽅案最近在⼀个项⽬中需要⽤到Excel⽂件导⼊数据库的功能,本⼈很懒,所以到⽹上搜了⼀堆⽅法,但是通过对⽐,觉得⼀下三种是⽐较好⽤或者不是很常见的⽅法,希望对⼤家有所帮助。
⽅案⼀:通过OleDB⽅式获取Excel⽂件的数据,然后通过DataSet中转到SQL Server,这种⽅法的优点是⾮常的灵活,可以对Excel表中的各个单元格进⾏⽤户所需的操作。
1. openFileDialog = new OpenFileDialog();2. openFileDialog.Filter = "Excel files(*.xls)|*.xls";3.4. if(openFileDialog.ShowDialog()==DialogResult.OK)5. {6. FileInfo fileInfo = new FileInfo(openFileDialog.FileName);7. string filePath = fileInfo.FullName;8. string connExcel = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0";9.10. try11. {12. OleDbConnection oleDbConnection = new OleDbConnection(connExcel);13. oleDbConnection.Open();14.15. //获取excel表16. DataTable dataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);17.18. //获取sheet名,其中[0][1]...[N]: 按名称排列的表单元素19. string tableName = dataTable.Rows[0][2].ToString().Trim();20. tableName = "[" + tableName.Replace("'","") + "]";21.22. //利⽤SQL语句从Excel⽂件⾥获取数据23. //string query = "SELECT classDate,classPlace,classTeacher,classTitle,classID FROM " + tableName;24. string query = "SELECT ⽇期,开课城市,讲师,课程名称,持续时间 FROM " + tableName;25. dataSet = new DataSet();26.27. //OleDbCommand oleCommand = new OleDbCommand(query, oleDbConnection);28. //OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand);29. OleDbDataAdapter oleAdapter = new OleDbDataAdapter(query,connExcel);30. oleAdapter.Fill(dataSet,"gch_Class_Info");31. //从excel⽂件获得数据后,插⼊记录到SQL Server的数据表32. DataTable dataTable1 = new DataTable();33.34. SqlDataAdapter sqlDA1 = new SqlDataAdapter(@"SELECT classID, classDate,35. classPlace, classTeacher, classTitle, durativeDate FROM gch_Class_Info",sqlConnection1);36.37. //SqlCommandBuilder sqlCB1 = new SqlCommandBuilder(sqlDA1);38.39. sqlDA1.Fill(dataTable1);40.41. foreach(DataRow dataRow in dataSet.Tables["gch_Class_Info"].Rows)42. {43. DataRow dataRow1 = dataTable1.NewRow();44.45. dataRow1["classDate"] = dataRow["⽇期"];46. dataRow1["classPlace"] = dataRow["开课城市"];47. dataRow1["classTeacher"] = dataRow["讲师"];48. dataRow1["classTitle"] = dataRow["课程名称"];49. dataRow1["durativeDate"] = dataRow["持续时间"];50.51. dataTable1.Rows.Add(dataRow1);52. }53.54. Console.WriteLine("新插⼊ " + dataTable1.Rows.Count.ToString() + " 条记录");55. sqlDA1.Update(dataTable1);56.57. oleDbConnection.Close();58.59. }60. catch(Exception ex)61. {62. Console.WriteLine(ex.ToString());63. }64. }⽅案⼆:直接通过SQL语句执⾏SQL Server的功能函数将Excel⽂件转换到SQL Server数据库。
Excel表格里的数据导入SQLSERVER数据库

使用第三方工具
总结词
除了SQL Server自带的功能外,还有许多第三方工具可以帮助用户将Excel数据导入SQL Server。
详细描述
这些第三方工具通常提供了更多的功能和灵活性,例如支持更多的文件格式、自动映射列、数据清洗和转换等。 用户可以根据自己的需求选择合适的工具,如DataGrip、Tableau、Power BI等。
逻辑检查
检查数据是否符合业务逻 辑,如年龄字段是否合理。
参照完整性
检查外键引用是否有效, 关联的数据是否一致。
数据性能优化
索引优化
根据查询需求,为常用查询字段 建立合适的索引。
查询优化
优化导入后的查询语句,提高查询 效率。
数据分区
根据数据的特点和使用频率,对表 进行分区管理。
THANKS
感谢观看
02
Excel数据导入SQL Server的方法
使用SQL Server Integration Services (SSIS)
总结词
SSIS是SQL Server提供的一个强大的ETL工具,可以用来导入、导出和转换数据 。
详细描述
通过SSIS,用户可以创建一个数据流任务,将Excel文件作为源数据,然后将其导入 到SQL Server数据库中。在SSIS中,用户可以定义数据清洗、转换和加载的规则, 确保数据准确无误地导入到目标表中。
通过导入Excel数据到SQL Server, 可以自动化地完成数据清洗、转换 和加载等任务,减少手动操作的时 间和人力成本。
批量处理
导入大量数据时,使用SQL Server的批量导入功能可以显著 提高数据处理的效率,减少等待 时间。
保证数据一致性
数据格式统一
asp实现excel中的数据导入数据库

asp实现excel中的数据导⼊数据库asp实现excel中的数据导⼊数据库<% Response.CodePage=65001%><% Response.Charset="UTF-8" %><%wenjian = request.Form("select")'获取⽂件扩展名ext = FileExec(wenjian)'判断⽂件扩展名if ext <> "xls" thenresponse.Write("<script>alert('⽂件类型不对,请核实!');window.location.href='index.html';</script>")response.End()end ifDim objConn,objRSDim strConn,strSqlset objConn=Server.CreateObject("ADODB.Connection")set objRS=Server.CreateObject("ADODB.Recordset")excelFile = server.mappath(wenjian)'针对excel 2007strConn = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & excelFile & ";" & "Extended Properties=Excel 8.0;"objConn.Open strConnstrSql="SELECT * FROM [Sheet1$]"objRS.Open strSql,objConn,1,1objRS.MoveFirst%><!--#include file="conn.asp"--><%'循环excel中所有记录while not objRS.eofset rs = Server.CreateObject("Adodb.Recordset")'查询语句sql_s = "select * from ceshi where lname='" & objRS(0) & "' and old='" & objRS(1) & "' and sex='" & objRS(2) & "' and guojia='" & objRS(3) & "' and QQ='" & objRS(4) & "'" rs.open sql_s, conn, 1, 1'重复的数据不做录⼊操作if rs.eof then'插⼊语句'****excel中第⼀条不会被录⼊****sql = "insert into ceshi (lname, old, sex, guojia, QQ)values ('" & objRS(0) & "', '" & objRS(1) & "', '" & objRS(2) & "', '" & objRS(3) & "', '" & objRS(4) & "')"'执⾏插⼊conn.execute(sql)end ifobjRS.MoveNextrs.closeset rs = nothingwend'⼜到了各种关闭的时候conn.closeset conn = nothingobjRS.CloseobjConn.Closeset objRS = Nothingset objConn = Nothingresponse.Write("<script>alert('导⼊成功');window.location.href='index.html';</script>")response.End()Function FileExec(fileName)FileExec = Mid(fileName,Instr(fileName,".")+1,Len(fileName)-Instr(fileName,"."))End Function%>再分享⼀个简化版的代码wenjian=request.Form("floor")fileext=mid(wenjian,InStrRev(wenjian,".")+1)if lcase(fileext)<>"xls" thenresponse.write "<script>alert ('⽂件格式不对,请上传Excel⽂件');window.location.href='updateFloor.asp';</script>"response.endend ifset conne=server.CreateObject("ADODB.Connection")connStre="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath( ""&wenjian&"" )&";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';"conne.open connStreSqle="select * from [sheet1$] "Set rse = Server.CreateObject("ADODB.Recordset")rse.open sqle,conne,1,1'验证hang=2do while not rse.eof'名称不能为空if trim(rse(0))<>"" thenelsemess="第"& hang &"⾏名称为空,请检查!"response.Write"<script>alert('"& mess &"').window.location.href='updateFloor.asp'</script>"response.End()end ifrse.movenexthang=hang+1looprse.movefirstdo while not rse.eofset rst=server.CreateObject("adodb.recordset")sqlt="select * from Sellman"rst.open sqlt,conn,1,3rst.addnew()rst("CompanyName")=c2(rse(0))rst("CompanyInfo")=c2(rse(1))rst("address")=c2(rse(2))rst("tel")=c2(rse(3))&" "&c2(rse(7))rst("Fax")=c2(rse(4))rst("linkman")=c2(rse(5))rst("Homepage")=c2(rse(8))rst("Email")=c2(rse(6))rst.update()rst.closeset rst=nothingrse.movenextlooprse.closeset rse=nothingresponse.Write "<script>alert('导⼊成功!');location.href='updateFloor.asp';</script>"其实简单的说象access 数据库⼀样,把excel⽂件打开,再进⾏读再写到access中你要写到sqlserver中就把写的过程改⼀下就成了看下代码:dim conndim conn2set conn=CreateObject("ADODB.Connection")conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=;Data Source=c:\book1.mdb"set conn2=CreateObject("ADODB.Connection")conn2.Open "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=;Extended properties=Excel 5.0;Data Source=c:\book1.xls"sql = "SELECT * FROM [Sheet1$]"set rs = conn2.execute(sql)while not rs.eofsql = "insert into xxx([a],[b],[c],[d]) values('"& fixsql(rs(0)) &"','"& fixsql(rs(1)) &"','"& fixsql(rs(2)) &"','"& fixsql(rs(3)) &"')"conn.execute(sql)rs.movenextwendconn.closeset conn = nothingconn2.closeset conn2 = nothingfunction fixsql(str)dim newstrnewstr = strif isnull(newstr) thennewstr = ""elsenewstr = replace(newstr,"'","''")end iffixsql = newstrend function。
怎样把EXCEL文件资料导入SQL SERVER2008的数据库的表中

怎样把Excel文件资料导入SQL Server2008的数据库的表中1.Excel导入SQLserver的表中前,保证Excel的表中列的顺序和数据库表的列的顺序保持一致,如果该列没有值,可以为空白。
2.打开SQL企业管理器(Microsoft SQL Server Management Studio)建议用SA身边登陆,如果Windows NT用户具有同等权限也可以3.登陆服务后,展开数据库服务器,会在最底下找到“管理”选项,单击右键,选择“导入数据(I)”选项4.单击数据导入选项后,会出现导入向导画面,直接单击“下一步”5.选择数据如下图1)在选择数据源时,请选择Microsoft Excel,因为我们的主题就是Excel导入SQL server 2)浏览要导入的Excel文件路径3)选择您要导入的Excel版本4)单击“下一步”4)数据源类型的选择列表5).Excel版本选择列表6.选择导入的目标1).选择导入的目标服务器的名称,没有显示可以手工输入的2).身份验证,建议使用用户:sa密码:**********3).选择要导入数据的数据库(Database)4).单击“下一步”7.指定表复制查询,因为本文讲述的是Excel的导入不要写SQL查询,默认选择即可,单击“下一步”8.选择源表和源视图1)本文讲述的是从Excel导入,请选择对应的源表Sheet1$2)选择目标源,请选择您要导入的数据表的名称3)如果有需要预览源数据,请单击右下边的“预览(P)”4).数据源的预览效果,如果发现数据源与表的结构不一致时,请及时调整Excel的格式。
9.查看数据类型映射这一步基本是系统显示目标源的数据结构和类型其次选择出错的处理方案,失败,忽略单击“下一步”10.保持并运行,是否要立刻运行。
11.完成向导,执行操作并保存数据12.执行操作的结果报告13.数据库中执行查询操作的显示结果,检查导入的数据是否正确,如有问题及时调整。
asp将excel导入数据库的方法

asp将excel导入数据库的方法下面,由小编教你怎么用代码的方式用asp将excel导入到access 的数据库吧Excel中的数据导入到Access中,前提是在Access中的表已经建好。
dim conn dim conn2set conn=CreateObject("ADODB.Connection")conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=;Data Source=c:\book1.mdb"set conn2=CreateObject("ADODB.Connection")conn2.Open "Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:Database Password=;Extended properties=Excel 5.0;Data Source=c:\book1.xls"sql = "select * FROM [Sheet1$]" set rs = conn2.execute(sql) while not rs.eofsql = "insert into xxx([a],[bb],[c],[d]) values('"& fixsql(rs(0)) &"','"& fixsql(rs(1)) &"','"& fixsql(rs(2)) &"','"& fixsql(rs(3)) &"')"conn.execute(sql) rs.movenext wendconn.closeset conn = nothing conn2.closeset conn2 = nothingfunction fixsql(str) dim newstr newstr = strif isnull(newstr) then newstr = "" elsenewstr = replace(newstr,"'","'") end iffixsql = newstr end function导入到Sql Server数据库中时,如果Excel文件和数据库不在同一台服务器上时,请参考上面的代码。
数据库管理与应用将Excel数据导入SQL Server

将Excel数据导入SQL Server 首先将收集来的Excel文件放置在磁盘的某个位置,例如,d:\data\rpt1.xls。
通过SQL Server Management Studio,将其导入到SQL Server 2008数据库中。
操作步骤如下:(1)打开SQL Server Management Studio窗口,打开“数据库”节点。
(2)在要转换的数据库上右击鼠标,例如gsxsk数据库(可自行建一数据库gsxsk)。
在打开的快捷菜单上选择“任务” “导入数据”命令,打开“SQL Server导入和导出向导”对话框。
(3)单击“下一步”按钮,向导提示选择数据源,如图11-1所示。
在“数据源”下拉列表框中选择Microsoft Excel,表示将Excel数据导入到SQL Server中。
然后在“Excel连接设置”栏中,设置Excel文件的保存路径和Excel的版本。
图11-1 数据源界面
(4)单击“下一步”按钮,向导提示选择目标数据源,如图11-2所示。
在“目标”下拉列表中选择数据源类型,在“服务器”列表框中选择服务器,并设置验证模式。
在“数据库”下拉列表框中选择数据库。
图11-2 目标界面
(5)单击“下一步”按钮,向导提示用户指定表复制或者查询复制,如图11-3所示。
其中两个单选按钮的含义如下:。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
ASP实现 将Excel表格数据批量导入到SQLServer数据库
说明:
1. 被导入的工作表格, 默认以Sheet1命名, 当然也可以指定为其他的, 但必须与程序中的相符.
2. 被导入的工作表中,第⼀一列第⼀一行必须有数据.
3. 被导入的工作表中的列数要与程序中相符.
'定义打开Excel表格的函数
Function OpenExcel(path)
dim excel,rs,strsql
On Error Resume Next
Set rs = Server.CreateObject("ADODB.RecordSet")
Set excel = Server.CreateObject("ADODB.Connection")
excel.Open "Driver={Microsoft Excel Driver (*.xls)};DBQ=" & path
If Err.number<> 0 Then
Response.Write "请检查上传的Excel文件内部格式,文件无法打开,导入失败!"
Response.End
End If
strsql = "SELECT * FROM [Sheet1$]" '在这里指定工作薄名称,默认是Sheet1$
Set rs = excel.Execute(strsql)
Set OpenExcel = rs
End Function
'读取文件中的内容
Dim rsInfo
Set rsInfo = Server.CreateObject("ADODB.RecordSet")
Set rsInfo = OpenExcel("E:/a.xls")'这里的文件路径请用Server.Path来获取
'检查读取结果
If rsInfo.State<> 1 Then
Response.Write "请检查Excel文件中的工作表命名是否为Sheet1,导入失败!"
Response.End
End If
If rsInfo.EOF And rsInfo.BOF Then
Response.Write "没有找到Excel表中的数据,导入失败!"
Response.End
End If
If IsNull(rsInfo.Fields(0)) or Trim(rsInfo.Fields(0))="" Then
Response.Write "没有找到Excel表中的数据,导入失败!"
Response.End
End If
'这里指定导入数据的列数,列数少了退出
If rsInfo.Fields.Count< 7 Then
Response.Write "Excel表中的数据列数不正确,导入失败!"
Response.End
End If
'创建数据库连接
dim dbrs,conn,sql
Set conn = Server.CreateObject("ADODB.Connection")
Set dbrs = Server.CreateObject("ADODB.Recordset")
'注: G_DB_ConnectString是连接数据库的字符串,自己定义
conn.ConnectionString = G_DB_ConnectString
conn.Open '打开数据库连接
'创建临时表
sql = "IF EXISTS (SELECT * FROM sysobjects WHERE xtype='U' and name='tmp_PartRes') "
sql = sql & "BEGIN Drop table tmp_PartRes END "
sql = sql & "Create table tmp_PartRes([ID] int identity(1,1),"
sql = sql & "PartID varchar(100),Brand varchar(100),[Package] varchar(100),"
sql = sql & "BatchNo varchar(100),[Price] varchar(100),[Stock] varchar(100) default('0'),"
sql = sql & "Brief varchar(100),StockFlag int default(1),"
sql = sql & "SuperFlag int default(1),SaleFlag int default(1))"
conn.execute sql
'取表结构 注意: 只取表的结构, 不要数据, 因为我这个是刚创建的临时表, 没有数据,
'如果表中存在数据, 要注意加上条件句, 防止取到数据 如: where ID = -1
sql = "SELECT * FROM tmp_PartRes"
dbrs.CursorLocation = 3'⼀一定要设置为3
dbrs.Open sql,conn, 3, 4'这里的参数必须是3和4
'取到表结构后, 必须要把活动连接及数据库连接关闭,这个很重要, 否则导入速度特慢.
Set dbrs.ActiveConnection = Nothing
conn.close
'提取Excel中的数据, 将excel中的数据放入到数据库表中.
While Not rsInfo.EOF
If Trim(rsInfo.Fields(0))<> "" Then
dbrs.AddNew
dbrs("PartID") = Ucase(Trim(rsInfo.Fields(0)))
dbrs("Brand") = Trim(rsInfo.Fields(1))
dbrs("Package") = Trim(rsInfo.Fields(2))
dbrs("BatchNo") = Trim(rsInfo.Fields(3))
dbrs("Price") = Trim(rsInfo.Fields(4))
If Trim(rsInfo.Fields(5))<>"" Then
dbrs("Stock") = Trim(rsInfo.Fields(5))
Else
dbrs("Stock") = "0"
End If
dbrs("Brief") = Trim(rsInfo.Fields(6))
End If
rsInfo.MoveNext
Wend
'更新记录集到数据库临时表
conn.Open'打开连接
dbrs.ActiveConnection = conn
dbrs.UpdateBatch'批量更新函数
'更新完成后, 关闭连接
dbrs.Close
Set dbrs = Nothing
rsInfo.Close
Set rsInfo = Nothing。