1. ASP怎样把excel上传到远程服务器后再导入到sql Server
哈哈
刚好我也在做这个案例
<%'sql 连接驱动
dim conn,connstr,time1,time2,mdb
time1=timer
dim aa
aa=request.form("EXCEL") '获取传递过来的值
Dim StrConnect,cc
Dim objConn
Dim rs
Dim Sql
cc=0
'Excel连接驱动
aaa="provider=Microsoft.Jet.OLEDB.4.0; Data Source="&aa&";Extended Properties=Excel 8.0"
set StrConnect=CreateObject("ADODB.Connection")
StrConnect.Open aaa
Set objConn=CreateObject("ADODB.Connection")
objConn.Open StrConnect
'注意 表名一定要以下边这种格试"[表名$]"书写
Set rs = Server.CreateObject("ADODB.Recordset")
Sql="select * from [sheet1$]"
rs.Open Sql,StrConnect,2,2
IF rs.Eof And Rs.Bof Then
response.Write("<script>alert('没有资料可以导入!');history.go(-1)</script>")
else
Do While Not rs.EOF
if rs(0)<>"" then
'插入SQL2000里
set rssql=server.CreateObject("adodb.recordset")
rssql.Open "select * from a_sell where PartNo='"&rs(0)&"'",conn,1,3
if not rssql.recordcount=0 then
response.write ""
else
rssql.AddNew
rssql(1)=rs(0)
rssql(2)=rs(1)
rssql(3)=rs(2)
rssql(4)=rs(3)
rssql(5)=rs(4)
rssql(6)=rs(5)
rssql(7)=rs(6)
rssql(8)=rs(7)
rssql.Update
end if
end if
Rs.MoveNext
Loop
end if
response.Write"<script language=javascript>alert('资料导入成功!\n重复数据未导入');history.go(-1)</script>"
%>
2. 在ASP中如何将Excel表中数据导入到SQL2000中
上边那个Function Open_Conn(SqlDatabaseName,SqlPassword,SqlUsername,SqlLocalName,SqlConn)
是连接sql数据库的函数,可以这样调用:
Call Open_Conn("Shat_EDG","sa","sa","(local)",SqlConn) '打开SQL Server数据库连接
连接Excel的连接函数要重新写的,可以这样写:
function open_excel_conn(filename)
on error resume next
Set conn=server.createobject("adodb.connection")
badgirl="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="&Server.Mappath(filename)&";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';"
conn.open badgirl
If Err.Number <> 0 Then
Response.write "不能打开指定的Excel,请查实!<a href='upexcel.htm'>返回</a>"
Response.end
else
On Error GoTo 0
end if
end function
你可以在代码的最后继续写
call open_excel_conn(Trim(Request("File")))
3. 上传excel文件并将数据导入到sql server数据库
可以用ASP实现,思路:
ASP上传Excel文件并导入数据到SQL数据库,程序一共分二步操作,第一步是上传文件,上传成功后再点击“导入数据”,Excel数据将被导入到SQL的表中,操作时要注意放置程序的目录必须有足够权限,否则程序报错。
4. asp怎么上传excel并导入sql server 2005
两种方法:
1、使用DTS方式导入
2、创建Excel数据库对象,然后循环从Excel工作簿里拿数据插入到SQL2005
两种方法我都会
但是,没有任何一个通用的导入办法,都需要写程序控制、校验、容错、返回错误信息
5. asp.net实现excel导入到sql
首先这个文件必须上传到服务器,然后读取里面的内容放在ds里面,然后在导入sql
具体做法:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Configuration;
namespace ETable
{
/// <summary>
/// ETable 的摘要说明。
/// </summary>
public class ETable : System.Web.UI.Page
{
protected System.Web.UI.HtmlControls.HtmlInputFile File1;
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.DataGrid DataGrid1;
public Random rd;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{
if (File1.PostedFile!=null)
{ rd=new Random(1);
string filename=DateTime.Now.Date.ToString("yyyymmdd")+DateTime.Now.ToLongTimeString().Replace(":","")+rd.Next(9999).ToString()+".xls";
File1.PostedFile.SaveAs(@Server.MapPath("file/")+filename);
//Response.Write(File1.PostedFile.FileName.ToString());
//Response.Write("上传成功");
Label1.Text="文件名为"+filename;
string conn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source ="+Server.MapPath("file")+"/"+filename+";Extended Properties=Excel 8.0" ;
OleDbConnection thisconnection=new OleDbConnection(conn);
thisconnection.Open();
string Sql="select * from [Sheet1$]";
OleDbDataAdapter mycommand=new OleDbDataAdapter(Sql,thisconnection);
DataSet ds=new DataSet();
mycommand.Fill(ds,"[Sheet1$]");
thisconnection.Close();
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
string conn1="User ID=sa;Data Source=127.0.0.1;Password=sa;Initial Catalog=index;Provider=SQLOLEDB.1;";
OleDbConnection thisconnection1=new OleDbConnection(conn1);
thisconnection1.Open();
int count=ds.Tables["[Sheet1$]"].Rows.Count;
for (int i=0;i<count;i++)
{
string id,id_1,id_2,id_3;
id=ds.Tables["[Sheet1$]"].Rows[i]["id"].ToString();
id_1=ds.Tables["[Sheet1$]"].Rows[i]["id_1"].ToString();
id_2=ds.Tables["[Sheet1$]"].Rows[i]["id_2"].ToString();
id_3=ds.Tables["[Sheet1$]"].Rows[i]["id_3"].ToString();
string excelsql="insert into excel(id,id_1,id_2,id_3) values ('"+id+"','"+id_1+"','"+id_2+"','"+id_3+"') ";
OleDbCommand mycommand1=new OleDbCommand(excelsql,thisconnection1);
mycommand1.ExecuteNonQuery();
}
Response.Write("更新成功");
thisconnection1.Close();
//FileStream fileStream = new FileStream(@Server.MapPath("file/")+filename);
System.IO.File.Delete(@Server.MapPath("file/")+filename);
}
}
}
}
C#
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Configuration;
namespace ETable
{
/// <summary>
/// ETable 的摘要说明。
/// </summary>
public class ETable : System.Web.UI.Page
{
protected System.Web.UI.HtmlControls.HtmlInputFile File1;
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.DataGrid DataGrid1;
public Random rd;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{
if (File1.PostedFile!=null)
{ rd=new Random(1);
string filename=DateTime.Now.Date.ToString("yyyymmdd")+DateTime.Now.ToLongTimeString().Replace(":","")+rd.Next(9999).ToString()+".xls";
File1.PostedFile.SaveAs(@Server.MapPath("file/")+filename);
//Response.Write(File1.PostedFile.FileName.ToString());
//Response.Write("上传成功");
Label1.Text="文件名为"+filename;
string conn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source ="+Server.MapPath("file")+"/"+filename+";Extended Properties=Excel 8.0" ;
OleDbConnection thisconnection=new OleDbConnection(conn);
thisconnection.Open();
string Sql="select * from [Sheet1$]";
OleDbDataAdapter mycommand=new OleDbDataAdapter(Sql,thisconnection);
DataSet ds=new DataSet();
mycommand.Fill(ds,"[Sheet1$]");
thisconnection.Close();
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
string conn1="User ID=sa;Data Source=127.0.0.1;Password=sa;Initial Catalog=index;Provider=SQLOLEDB.1;";
OleDbConnection thisconnection1=new OleDbConnection(conn1);
thisconnection1.Open();
int count=ds.Tables["[Sheet1$]"].Rows.Count;
for (int i=0;i<count;i++)
{
string id,id_1,id_2,id_3;
id=ds.Tables["[Sheet1$]"].Rows[i]["id"].ToString();
id_1=ds.Tables["[Sheet1$]"].Rows[i]["id_1"].ToString();
id_2=ds.Tables["[Sheet1$]"].Rows[i]["id_2"].ToString();
id_3=ds.Tables["[Sheet1$]"].Rows[i]["id_3"].ToString();
string excelsql="insert into excel(id,id_1,id_2,id_3) values ('"+id+"','"+id_1+"','"+id_2+"','"+id_3+"') ";
OleDbCommand mycommand1=new OleDbCommand(excelsql,thisconnection1);
mycommand1.ExecuteNonQuery();
}
Response.Write("更新成功");
thisconnection1.Close();
}
}
}
}
6. asp中怎么导入excel到SQL中
Set db = Server.CreateObject("ADODB.Connection")
db.Open "Driver={Microsoft Excel Driver (*.xls)};Dbq=" & Server.MapPath(FileName)
'打开记录集,表名一定要以"[表名$]"的格式
strSql="Select * From [Sheet1$]"
Set rsexcel=db.Execute(strSql)
Set rs = Server.CreateObject("ADODB.RecordSet")
SQL = "Select * From [users]"
rs.Open SQL, Conn, 1, 3
N = rs.fields.count-1'数据表字段数
M = rsexcel.fields.count-1'excel表里字段数
Redim L(N)'定义数据表数组
Redim arr(M)'定义excel表数组
'把数据表里的字段表存入数组L中
For k=0 To N
L(k) = Rs(k).name
next
'把excel表里的字段存入数组arr中
for p=0 to M
arr(p) = rsexcel(p).name
next
'取数组长度
x=UBound(l)
y=UBound(arr)
j=0
startime=timer() '开始时间
Do While Not rsexcel.EOF
rs.AddNew
'循环读取所有行
for i=6 to x'对数据表进行循环 rs(0)是 id 所以跳过
if l(i)=arr(j) then'通过数组判断两表字段是否相同,如相同对其进行赋值,不相同置0
if Trim(rsexcel(j))<>"" then
'response.write Trim(rsexcel(j))&"|"
rs(i)=Trim(rsexcel(j))
else
rs(i)=0
end if
if j< M then '当execl表数据是最后一项时不能在加1了
j=j+1
else
j=j
end if
else
rs(i)=0
end if
rs(3)=typeid
Next
rsexcel.MoveNext
rs.update
j=0
Loop
endtime=timer()
'关闭对象
rsexcel.Close
Set rsexcel=nothing
db.Close
Set db=Nothing
7. ASP代码中如何把EXCEL数据导入到SQL SERVER数据库中
'定义打开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
8. asp.net excel数据导入sql数据库
public static DataSet CreateDataSource()
{
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() != DialogResult.OK)
return null;
string filename = dialog.FileName;
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + filename +
";Extended Properties=Excel 8.0;";
try
{
OleDbConnection conn = new OleDbConnection(strConn);
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [数据$]", strConn);
DataSet myDataSet = new DataSet();
myCommand.Fill(myDataSet);
return myDataSet;
}
catch (Exception ex )
{
MessageBox.Show("打开文件时出错:" + ex.Message);
return null;
}
}
//sql 语句说明 "SELECT * FROM [数据$]",其中 “数据”表示excel中sheet的名称,
如:excel文件中有个叫"Sheet1"的标签页,SQL语句为 SELECT * FROM [Sheet1$]",excel的列会自动转化成DataTable的列,支持中文,会自动判断数据行。
每次只能打开一个sheet。
有了上面的数据,你再foreach 插入到SQL中去
9. asp 通过web方式将excel表的内容导入到sql数据库
用asp连接excel表
connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="&Server.MapPath(PatnNow)&";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"""
读取表中内容
'注意 表名一定要以下边这种格试 "[表名$]" 书写
Sql="Select * From [t_proct$] "
'=====================ASP读取EXCEL注事项===========================
'i)将Excel97或Excel2000生成的XLS文件(book)看成一个数据库,其中的每一个工作表(sheet)看成数据库表
'ii)ADO假设Excel中的第一行为字段名.所以你定义的范围中必须要包括第一行的内容
'iii)Excel中的行标题(即字段名)不能够包含数字. Excel的驱动在遇到这种问题时就会出错的。例如你的行标题名为“F1”
'iiii)如果你的Excel电子表格中某一列同时包含了文本和数字的话,那么Excel的ODBC驱动将不能够正常, 处理这一行的数据类型,
'你必须要保证该列的数据类型一致
我有个demo,有需要留个email我给你
10. asp中如何将excel数据导入到sql数据表中
怎样将数据从Excel导入到SQL Server中
(1)
<%
sub dataIntoSqlServer_ceritificate(strFileName,strSheetName,myConn)
'定义
dim myConnection
dim strName
dim rsXsl,rsSql
dim myConn_Xsl
dim cmd
dim i,j
dim maxId
strName = strFileName
set myConnection = Server.CreateObject("ADODB.Connection")
set rsXsl = Server.CreateObject("ADODB.Recordset")
set rsSql = Server.CreateObject("ADODB.Recordset")
set cmd = server.CreateObject("ADODB.Command")
cmd.ActiveConnection = myConn
myConn_Xsl = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strName & _
";Extended Properties=Excel 8.0"
'打开连接
myconnection.open myConn_Xsl
'打开表
str_Xsl = "select * from [" & strSheetName & "$]"
rsXsl.open str_Xsl,myconnection,1,1
j = 1
Do while not rsXsl.eof
'取出最大值
str_sql = "select Max(id) as maxId from exceltosql"
rsSql.open str_Sql,myConn,1,3
if Not rsSql.eof then
if not isNull(rsSql("maxId")) then
maxId=CLng(rsSql("maxId")) + 1
else
maxId = 1
end if
else
maxId = 1
end if
rsSql.close '//关闭对象
'加入数据库
str_Sql = "insert into exceltosql values(" & maxId&",'"&rsXsl(1)&"','" & rsXsl(2)&"')"
cmd.CommandText = str_Sql
cmd.Excute()
''''''''''''''''''''''''''''''''''''''''''
j = j + 1
rsXsl.moveNext
loop
response.write "共导入 " & j_1 & " 条记录.<br>"
response.write "<a href=# onclick='self.close();'>关闭窗口</a>"
set rsXsl = nothing
set rsSql = nothing
set myconnection = nothing
set cmd = nothing
end sub
(2)
'调用方法
<%
file1 = "c:\excelexample.xls"
myconn = "DRIVER={SQL SERVER};SERVER=(local);uid=sa;pwd=sa;DATABASE=aspbook"
dataIntoSqlServer_ceritificate file1,"sheet1",myconn
%>