從EXCEL匯入資料到SQL SERVER

2022-04-03 07:41:50 字數 1861 閱讀 1712

介紹兩種途徑將資料從excel中匯入到sql server。

一、        在程式中,用ado.net。**如下:

//連線串

string strconn = "provider=microsoft.jet.oledb.4.0;extended properties=excel 8.0;data source=" + [excel檔案,含路徑] + ";";

oledbconnection conn = new oledbconnection(strconn);

conn.open();

datatable dtschema = conn.getoledbschematable(oledbschemaguid.tables,new object );

dataset ds = new dataset();

//乙個excel檔案可能有多個工作表,遍歷之

foreach( datarow dr in dtschema.rows )

string table = dr["table_name"].tostring();

string strexcel = "select * from [" + table + "]";

ds.tables.add(table);

oledbdataadapter mycommand = new oledbdataadapter(strexcel,conn);

mycommand.fill(ds,table);

conn.close();

這樣,讀取出來的資料就藏在dataset裡了。

採用這種方式,資料庫所在機器不必裝有excel。

二、        在查詢分析器裡,直接寫sql語句:

如果是匯入資料到現有表,則採用

insert into 表 select * from openrowset('microsoft.jet.oledb.4.0'

,'excel 5.0;hdr=yes;database=c:\test.xls',sheet1$)

的形式如果是匯入資料並新增表,則採用

select * into 表 from openrowset('microsoft.jet.oledb.4.0'

,'excel 5.0;hdr=yes;database=c:\test.xls',sheet1$)

的形式。

以上語句是將excel檔案裡sheet1工作表中所有的列都讀進來,如果只想導部分列,可以

insert into 表(a1,a2,a3) select a1,a2,a3 from openrowset('microsoft.jet.oledb.4.0'

,'excel 5.0;hdr=yes;database=c:\test.xls',sheet1$)

其實可以將openrowset('microsoft.jet.oledb.4.0'

,'excel 5.0;hdr=yes;database=c:\test.xls',sheet1$)當成乙個表,例如我就寫過這樣乙個句子:

insert into eval_channel_employee(channel,employee_id)

select case a.渠道 when 'diy' then 1 when 'rdc' then 0 when 'kcm' then 2 else 3 end

,b.id from

openrowset('microsoft.jet.oledb.4.0'

,'excel 5.0;hdr=yes;database=c:\temp\name.xls',sheet1$) as a,pers_employee b

where a.員工編碼=b.code

不管是哪種方式,哪種途徑,系統都會預設將第一行上的內容作為欄位名。

從EXCEL匯入資料到SQL SERVER

從excel匯入資料到sql server 左直拳 介紹兩種途徑將資料從excel中匯入到sql server。一 在程式中,用ado.net。如下 連線串 string strconn provider microsoft.jet.oledb.4.0 extended properties exc...

從EXCEL匯入資料到SQL SERVER

從excel匯入資料到sql server 左直拳 介紹兩種途徑將資料從excel中匯入到sql server。一 在程式中,用ado.net。如下 連線串 string strconn provider microsoft.jet.oledb.4.0 extended properties exc...

從excel匯入資料到資料庫

建立connection物件的資料來源連線字串 provider microsoft.jet.oledb.4.0 data source excel 檔案物理路徑 extended properties excel 8.0 dataadapter物件中的sql語句應為 select 字段列表 fro...