當前位置:首頁 » 操作系統 » excel導入資料庫net

excel導入資料庫net

發布時間: 2022-02-16 07:08:31

⑴ C#.NET Excel文件數據導入sql Server資料庫完整代碼

在日常的項目中,Excel,Word,txt等格式的數據導入到資料庫中是很常見

這里將分為.net導入Sql Server,Oracle資料庫和WinForm導入Sql Server,Oracle資料庫。

實現的基本思想:

1,先使用FileUpload控制項fuload將Excel文件上傳到伺服器上得某一個文件夾

2,使用OleDb將已經上傳到伺服器上的Excel文件讀出來,這里將Excel文件當做一個資料庫來讀。在聯系資料庫語句中,Data Source就是該文件在伺服器上得物理路徑

3,將第二步中讀出的數據以DataTable對象返回。

4,遍歷DataTable對象,然後到Sql Server資料庫中查詢,是否存在該條數據。如果存在,可以做更新,或者不做處理;如果不存在,則插入數據。

注意:在遍歷DataTable的時候,可是使用dt.Rows[i]["Name"].ToString();Name為Name列的表頭,所以Excel中列的順序就無關緊要了。當然,前提是你知道Excel里列中各表頭的名字。如果Excel中列的順序固定,即可按下面代碼中的方式進行。

添加的引用:

usingSystem;
usingSystem.Data;
usingSystem.Data.OleDb;
usingSystem.Data.SqlClient;
usingSystem.IO;
usingSystem.Text;
usingSystem.Web;
usingSystem.Web.UI;
privateDataTablexsldata()
{
if(fuload.FileName=="")
{
lbmsg.Text="請選擇文件";
returnnull;
}
stringfileExtenSion;
fileExtenSion=Path.GetExtension(fuload.FileName);
if(fileExtenSion.ToLower()!=".xls"&&fileExtenSion.ToLower()!=".xlsx")
{
lbmsg.Text="上傳的文件格式不正確";
returnnull;
}
try
{
stringFileName="App_Data/"+Path.GetFileName(fuload.FileName);
if(File.Exists(Server.MapPath(FileName)))
{
File.Delete(Server.MapPath(FileName));
}
fuload.SaveAs(Server.MapPath(FileName));
//HDR=Yes,這代表第一行是標題,不做為數據使用,如果用HDR=NO,則表示第一行不是標題,做為數據來使用。系統默認的是YES
stringconnstr2003="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="+Server.MapPath(FileName)+";ExtendedProperties='Excel8.0;HDR=Yes;IMEX=1;'";
stringconnstr2007="Provider=Microsoft.ACE.OLEDB.12.0;DataSource="+Server.MapPath(FileName)+";ExtendedProperties="Excel12.0;HDR=YES"";
OleDbConnectionconn;
if(fileExtenSion.ToLower()==".xls")
{
conn=newOleDbConnection(connstr2003);
}
else
{
conn=newOleDbConnection(connstr2007);
}
conn.Open();
stringsql="select*from[Sheet1$]";
OleDbCommandcmd=newOleDbCommand(sql,conn);
DataTabledt=newDataTable();
OleDbDataReadersdr=cmd.ExecuteReader();

dt.Load(sdr);
sdr.Close();
conn.Close();
//刪除伺服器里上傳的文件
if(File.Exists(Server.MapPath(FileName)))
{
File.Delete(Server.MapPath(FileName));
}
returndt;
}
catch(Exceptione)
{
returnnull;
}
}

protectedvoidBtn_Export_Excel_To_DB_Click(objectsender,EventArgse)
{
try{

DataTabledt=xsldata();

//dataGridView2.DataSource=ds.Tables[0];
interrorcount=0;//記錄錯誤信息條數
intinsertcount=0;//記錄插入成功條數

intupdatecount=0;//記錄更新信息條數

stringstrcon="server=localhost;database=database1;uid=sa;pwd=sa";
SqlConnectionconn=newSqlConnection(strcon);//鏈接資料庫
conn.Open();

for(inti=0;i<dt.Rows.Count;i++)
{
stringName=dt.Rows[i][0].ToString();//dt.Rows[i]["Name"].ToString();"Name"即為Excel中Name列的表頭
stringSex=dt.Rows[i][1].ToString();
intAge=Convert.ToInt32(dt.Rows[i][2].ToString());
stringAddress=dt.Rows[i][3].ToString();
if(Name!=""&&Sex!=""&&Age!=0&&Address!="")
{
SqlCommandselectcmd=newSqlCommand("selectcount(*)fromuserswhereName='"+Name+"'andSex='"+Sex+"'andAge='"+Age+"'andAddress="+Address,conn);
intcount=Convert.ToInt32(selectcmd.ExecuteScalar());
if(count>0)
{
updatecount++;
}
else
{
SqlCommandinsertcmd=newSqlCommand("insertintousers(Name,Sex,Age,Address)values('"+Name+"','"+Sex+"',"+Age+",'"+Address+"')",conn);
insertcmd.ExecuteNonQuery();
insertcount++;
}
}
else
{
errorcount++;
}
}
Response.Write((insertcount+"條數據導入成功!"+updatecount+"條數據重復!"+errorcount+"條數據部分信息為空沒有導入!"));
}
catch(Exceptionex)
{

}
}

⑵ ASP.NET中如何將Excel表中的數據導入到資料庫中

ASP.NET中將Excel表中的數據導入到資料庫中的方法是利用可視化界面工具直接選擇欄位映射導入。
1)接受數據導入的表已經存在。
insert into t1 select * from OPENROWSET('MICROSOFT.JET.OLEDB.4.0' ,
'Excel 5.0;HDR=YES;DATABASE=c:\\test.xls',sheet1$);
2)導入數據並生成表。
select * into t1 from OPENROWSET('MICROSOFT.JET.OLEDB.4.0',
'Excel 5.0;HDR=YES;DATABASE=c:\\test.xls',sheet1$);

3) 導入Excel中指定的列到資料庫表中指定的列。
INSERT INTO t1(a1,a2,a3) SELECT a1,a2,a3 FROM OPENROWSET'MICROSOFT.JET.OLEDB.4.0' ,'Excel5.0; HDR=YES; DATABASE=c:\\test.xls',sheet1$);
需要注意的地方。
1)外圍應用配置器的設置。
從「功能外圍應用配置器」中選擇「啟動 OPENROWSET 和 OPENDATASOURCE 支持」選項。
2)關閉Excel表。
如果在導入時要導入的Excel表格處於打開狀態,會提示:
「無法初始化鏈接伺服器 "(null)" 的 OLE DB 訪問介面 "microsoft.jet.oledb.4.0" 的數據源對象。」
3)導入數據時,Excel的首行會作為表頭,若導入到已存在的資料庫表,則忽略首行。

⑶ 請教.net高手 有關Excel導入sql資料庫的問題(c#)(急用)

protected void Button1_Click(object sender, System.EventArgs e)
{
string XLS_Path="";
string XLS_Name = MakeFileName();
string fileExtName = "";
if(File1.PostedFile.ContentLength >0)
{
try
{
fileExtName = File1.PostedFile.FileName.Substring(File1.PostedFile.FileName.LastIndexOf("."));
if(fileExtName!=".xls"||fileExtName.Length<1)
{
Response.Write( "<script language=javascript>alert('數據導入失敗.可能是文件格式或路徑不正確!!!');</script>");
return;
}
File1.PostedFile.SaveAs(Server.MapPath("../uploadexcel/")+XLS_Name+fileExtName);
XLS_Path =Server.MapPath("../uploadexcel/")+ XLS_Name+fileExtName;
}
catch(Exception ex)
{
Response.Write(ex.ToString());
}
}
else
{
Response.Write( "<script language=javascript>alert('請選擇文件後再上傳!!!');</script>");
return;
}
string ConStr=System.Configuration.ConfigurationManager.AppSettings["ConnString"];
SqlConnection Conn=new SqlConnection(ConStr);
string mystring="Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '"+XLS_Path+"'"+";Extended Properties=Excel 8.0";
OleDbConnection cnnxls = new OleDbConnection (mystring);
OleDbDataAdapter myDa =new OleDbDataAdapter("select * from [Sheet1$]",cnnxls);
DataSet myDs =new DataSet();
try
{
myDa.Fill(myDs);
}
catch
{
Response.Write( "<script language=javascript>alert('數據導入失敗,請檢查!!');</script>");
return;
}
if(myDs.Tables[0].Rows.Count<=0)
{
Response.Write( "<script language=javascript>alert('文件中可能沒有數據,請檢查後重新導入!');</script>");
return;
}

int []zjid=new int[myDs.Tables[0].Rows.Count];
string strSql = "";
string CnnString="Provider=SQLOLEDB;"+ConStr;
OleDbConnection conn =new OleDbConnection(CnnString);
OleDbCommand myCmd =null;

⑷ APS.NET怎樣把EXCEL導入到資料庫

public static void DataTableToDB()
{
string _strExcelFileName = @"D:\example.xls";
DataTable dtExcel = ExcelToDataTable(_strExcelFileName,"Sheet1");
//這個dtExcel 里頭就是excel的數據 excel中的第一行默認為表名

}

二、把Excel數據讀入DataTable
public static DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strExcelFileName + ";" +"Extended Properties=Excel 5.0;";
string strExcel = string.Format("select * from [{0}$]", strSheetName);
DataSet ds = new DataSet();

using (OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
adapter.Fill(ds, strSheetName);
conn.Close();
}

return ds.Tables[strSheetName];
}

⑸ excel中多個sheet怎麼導入sql資料庫 .net

Try
Dim xlsConn As String, xlscmd As String, SourcePath As String = Server.MapPath & "~/Excel1.xls"
Dim ExcelConnection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" & SourcePath & "'; Extended Properties=""Excel 12.0 Xml; HDR=Yes""")

xlsConn = ExcelConnection.ConnectionString

Using connection As New OleDbConnection(xlsConn)
connection.Open() : ExcelConnection.Open()
Dim SheetName As String = "Sheet2"

xlscmd = "SELECT [columnA] FROM [" & SheetName & "$]"

Dim command As New OleDbCommand(xlscmd, connection)

' Create DbDataReader to Data Worksheet
Using dr As OleDbDataReader = command.ExecuteReader()

Dim cmd As String = "truncate table " & tableName
SqlCmd = New OleDbCommand(cmd, SqlConn)
SqlCmd.ExecuteNonQuery()

' Bulk Copy to SQL Server
Dim sqlConnectionString As String
sqlConnectionString = "Data Source=" & .SqlConn.DataSource & ";Initial Catalog=" & SqlConn.Database & ";Persist Security Info=True;User ID=sa;Password="

Using bulkCopy As New SqlBulkCopy(sqlConnectionString)
bulkCopy.DestinationTableName = "tableName"
bulkCopy.WriteToServer(dr)
Return True
End Using
End Using
End Using

Catch ex As Exception
Return False
End Try

大致是這樣。。。

⑹ 如何實現asp.net中將Excel導入資料庫多個表中

用OLEDB進行Excel文件數據讀取並返DataSet數據集其幾點需要注意:

1.連接字元串參數IMEX 值:
0 is Export mode
1 is Import mode
2 is Linked mode (full update capabilities)
IMEX3值:IMEX=2 EXCEL文檔同含字元型數字型比第C列3值2數值型 1231字元型 ABC導入
頁面報錯庫顯示數值型123字元型ABC則呈現空值IMEX=1述情況發庫確呈現 123 ABC.
2.參數HDR值:
HDR=Yes代表第行標題做數據使用 用HDR=NO則表示第行標題做數據使用系統默認YES
3.參數Excel 8.0
於Excel 97版本都用Excel 8.0

#region獲取exceldataset,即名excel_ds
stringexcelFilePath=openFileDialog1.FileName;//彈文件選取窗口獲取EXCEL文件路徑
stringstrConn="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="+excelFilePath+";ExtendedProperties="Excel8.0;HDR=YES;IMEX=1"";
OleDbConnectionOleconn=newOleDbConnection(strConn);
stringstrExcel="";
OleDbDataAdapterexcelCommand=null;
DataSetexcel_ds=newDataSet();
strExcel="select*from[sheet1$]";
try
{
Oleconn.Open();
excelCommand=newOleDbDataAdapter(strExcel,Oleconn);
excelCommand.Fill(excel_ds,"exdtSource");//dataset
}
catch(System.Exceptionex)
{
MessageBox.Show("導入錯:"+ex,"錯誤信息");
}
finally
{
Oleconn.Close();
Oleconn.Dispose();
}
#endregion

⑺ c#.net從excel表導入數據到網頁而達到快速增加資料庫行的操作

這樣的問題很多了
你需要一個放一個fileupload控制項 用來上傳excel ,還需要在項目里建一個文件夾用來存放你要上傳的excel 。因為系統總是先把文件傳到伺服器上再進行操作,而不是對每個人的桌面excel直接操作。
using System.Data.SqlClient;
using System.Data.OleDb; // 要加這兩句
public DataSet ExecleDs(string filenameurl, string table) // 這個函數就是將上傳的excel讀入dataset
{
string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + filenameurl + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'"; // 這里excel03 如要該成07版再問我或者網路
string strcom = "select *from [Sheet1$]";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataSet ds = new DataSet();
OleDbDataAdapter odda = new OleDbDataAdapter(strcom, conn);
odda.Fill(ds, table);
return ds;

}

protected void Button4_Click(object sender, EventArgs e) // 你的那個確定按鈕
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "server='CWJMXT-14\\SQLEXPRESS';database='E-test';uid='sa';pwd=『..'" ; // 你自己的資料庫連接
if (FileUpload1.HasFile == false)//HasFile用來檢查FileUpload是否有指定文件
{
Response.Write("<script>alert('請您選擇Excel文件')</script> ");
return;//當無文件時,返回
}
string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//System.IO.Path.GetExtension獲得文件的擴展名
if (IsXls != ".xls")
{
Response.Write("<script>alert('只可以選擇Excel文件')</script>");
return;//當選擇的不是Excel文件時,返回
}

con.Open();
string filename = FileUpload1.FileName; //獲取Execle文件名 DateTime日期函數
// Label2.Text = filename;
string savePath = Server.MapPath(("~\\upfiles\\") + filename);//Server.MapPath 獲得虛擬伺服器相對路徑
FileUpload1.SaveAs(savePath); //SaveAs 將上傳的文件內容保存在伺服器上
DataSet ds = ExecleDs(savePath, filename); //調用自定義方法
DataRow[] dr = ds.Tables[0].Select(); //定義一個DataRow數組
int rowsnum = ds.Tables[0].Rows.Count;
if (rowsnum == 0)
{
Response.Write("<script>alert('Excel表為空表,無數據!')</script>"); //當Excel表為空時,對用戶進行提示
}
else
{
for (int i = 0; i < dr.Length; i++)
{
//string pininputdate = dr[i]["].ToString();//日期 excel列名【名稱不能變,否則就會出錯】

string insertstr = "insert into item1(試題組別,試題類型,試題題目,選項A,選項B,選項C,選項D,正確答案,隨機或必出)values('" + dr[i][0].ToString() + "','" + dr[i][1].ToString() + "','" + dr[i][2].ToString() + "','" + dr[i][3].ToString() + "','" + dr[i][4].ToString() + "','" + dr[i][5].ToString() + "','" + dr[i][6].ToString() + "','" + dr[i][7].ToString() + "','" + dr[i][8].ToString() + "')"; //這里就是具體怎麼樣一行一行將dataset中的數據導入sql的 你也可以加一些其他判斷什麼的。 SqlCommand cmd = new SqlCommand(insertstr, con);
try
{
cmd.ExecuteNonQuery();
}
catch (MembershipCreateUserException ex) //捕捉異常
{
Response.Write("<script>alert('導入內容:" + ex.Message + "')</script>");
}

}
Response.Write("<script>alert('Excle表導入成功!');location='itemmaintain.aspx'</script>");
}
con.Close();
}

⑻ 怎樣將EXCEL表格數據通過C#.NET導入到SQL資料庫中

你完全可以把Excel當數據表一樣讀出來,然後再寫進Sql
讀Excel的方法:
string strConn = "provider=Microsoft.Jet.OLEDB.4.0;data source=Excel文件;Extended Properties=Excel 8.0;";

OleDbConnection oleConn = new OleDbConnection(strConn);
oleConn.Open();
string olestr = "select * from [Sheet1$]";
OleDbCommand oleComm = new OleDbCommand(olestr, oleConn);
oleComm.Connection = oleConn;
OleDbDataAdapter oleDa = new OleDbDataAdapter();
oleDa.SelectCommand = oleComm;
DataSet ds = new DataSet();
oleDa.Fill(ds);
foreach (DataRow row in ds.Tables["INFO"].Rows)
{
string userInfo = row[0].ToString().Trim();
}
oleConn.Close();

⑼ ASP.NET項目把Excel表中數據導入到資料庫!我用的是實體框架(Entity Framework)

用NPOI操作excel就很簡單,調用他的介面就可以。

⑽ 如何資料庫內容導入excel表格(C#/ASP.NET)

使用一些資料庫查詢工具,比如 pl/sql 或者 tode,都自帶數據導出為excel文件的功能

熱點內容
筆記本什麼配置能流暢運行cf 發布:2024-09-20 00:14:19 瀏覽:951
實測華為編譯器 發布:2024-09-19 23:50:52 瀏覽:821
linux匯總 發布:2024-09-19 23:46:39 瀏覽:452
阿里雲伺服器環境搭建教程 發布:2024-09-19 23:21:58 瀏覽:837
黃色文件夾圖標 發布:2024-09-19 23:19:22 瀏覽:684
mysql資料庫導出導入 發布:2024-09-19 23:00:47 瀏覽:183
lua腳本精靈 發布:2024-09-19 23:00:41 瀏覽:659
任務欄文件夾圖標 發布:2024-09-19 22:54:25 瀏覽:101
解壓來一波 發布:2024-09-19 22:46:36 瀏覽:933
mysqlpythonubuntu 發布:2024-09-19 22:46:27 瀏覽:501