當前位置:首頁 » 編程語言 » aspexcel上傳sql
擴展閱讀
怎麼清除預覽圖片的緩存 2022-11-30 14:15:11
c語言創建有序鏈表 2022-11-30 14:08:06

aspexcel上傳sql

發布時間: 2022-11-25 13:48:55

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
%>