asp.net中EXCEL数据导入到数据库的方法
本文实例讲述了asp.net中EXCEL数据导入到数据库的方法。分享给大家供大家参考。具体分析如下:
excel是办公中非常常用的一个办公表格了,但我们在开发中通常会需要直接把excel数据快速导入到数据库中了,这里整理了一个asp.net中EXCEL数据导入到数据库的例子供各位参考学习。
注意:EXCEL中的第一行不能导入。
下面是源码:IntoExcel.aspx:
<%@Page AutoEventWireup="true"CodeFile="IntoExcel.aspx.cs"Inherits="study_IntoExcel"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headid="Head1"runat="server">
<title>无标题页</title>
<scriptlanguage="javascript"type="text/javascript"><!--
//<!CDATA[
functioncheck(){
vark=//S+/.[xls]/;
if(!k.test(document.getElementById("fileId").value))
{
alert("只能上次xls格式的文件");
returnfalse;
}
returntrue;
}
//--></script>
</head>
<body>
<formid="form1"runat="server">
<div>
<p>
<asp:FileUploadID="fileId"runat="server"/>
<asp:ButtonID="Button1"runat="server"Text="上传"OnClientClick="returncheck()"onclick="Button1_Click"/></p>
</div>
</form>
</body>
</html>IntoExcel.aspx.cs
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Collections;
usingSystem.Configuration;
usingSystem.Data;
usingSystem.Web.Security;
usingSystem.Web.UI.HtmlControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.IO;
usingSystem.Data.OleDb;
usingSystem.Data.SqlClient;
usingSystem.Web.UI.WebControls;
publicpartialclassstudy_IntoExcel:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
}
///<summary>
///上传文件
///</summary>
///<paramname="sender"></param>
///<paramname="e"></param>
protectedvoidButton1_Click(objectsender,EventArgse)
{
stringfileName=fileId.FileName;
stringsavePath=Server.MapPath("~/file/");
FileOperatpr(fileName,savePath);
fileId.SaveAs(savePath+fileName);
DataOperator(fileName,savePath);
}
///<summary>
///数据操作
///</summary>
///<paramname="fileName"></param>
///<paramname="savePath"></param>
privatevoidDataOperator(stringfileName,stringsavePath)
{
stringmyString="Provider=Microsoft.Jet.OLEDB.4.0;DataSource= "+savePath+fileName+";ExtendedProperties=Excel8.0";
OleDbConnectionoconn=newOleDbConnection(myString);
oconn.Open();
DataSetds=newDataSet();
OleDbDataAdapteroda=newOleDbDataAdapter("select*from[Sheet1$]",oconn);
oda.Fill(ds);
oconn.Close();
DataSetOperator(ds,savePath+fileName);
}
///<summary>
///数据集操作
///</summary>
///<paramname="ds"></param>
privatevoidDataSetOperator(DataSetds,stringfilePath)
{
SqlConnectionconn=newSqlConnection("DataSource=SONYSVR;InitialCatalog=IAR_Factory_811;UserID=sa;Password=P@ssword");
conn.Open();
SqlTransactionstr=conn.BeginTransaction();//利用事务处理防止中断
intk=0;
if(ds.Tables[0].Rows.Count<1)
{
Response.Write("<script>alert('没有数据!')</script>");
return;
}
try
{
for(inti=0;i<ds.Tables[0].Rows.Count;i++)
{
string<strong><ahref="https://www.nhooo.com"title="sql"target="_blank">sql</a></strong>Str="insertintoIntoExcel(Tname,Tage,Taddress)values";
sqlStr+="('"+ds.Tables[0].Rows[i][0].ToString()+"',";
sqlStr+=ds.Tables[0].Rows[i][1].ToString()+",";
sqlStr+="'"+ds.Tables[0].Rows[i][2].ToString()+"')";
SqlCommandcmd=newSqlCommand(sqlStr,conn,str);
cmd.Transaction=str;
k+=cmd.ExecuteNonQuery();
}
str.Commit();
}
catch(Exceptionex)
{
Response.Write("发生异常,数据已回滚/n信息/n"+ex.Message);
str.Rollback();
}
finally
{
Response.Write("上传成功"+k+"条");
File.Delete(filePath);
}
}
///<summary>
///文件操作
///</summary>
///<paramname="fileName"></param>
///<paramname="savePath"></param>
privatevoidFileOperatpr(stringfileName,stringsavePath)
{
if(!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
if(File.Exists(savePath+fileName))
{
File.Delete(savePath+fileName);
}
}
}
Provider=Microsoft.Jet.OLEDB.4.0;DataSource="+savePath+";ExtendedProperties='Excel8.0;HDR=YES
Provider=Microsoft.Jet.OLEDB.4.0;;//连接驱动
DataSource="+savePath+";//数据库地址
ExtendedProperties='Excel8.0;//连接的是Excel8.0
HDR=YES;//有两个值:YES/NO,这2个值,说了你是否能直接读列名,NO,只可以读下标
IMEX=1;//解决数字与字符混合时,识别不正常的情况.这个读入数据库的方式不是最佳的,应该用office组件
select*from[Sheet1$]//引用EXCLE文件中sheet1工作表的内容
OleDB控件用的是OleDb的驱动程序,可以访问各种数据库
数据库中的字段:
createtableIntoExcel
(
Tidintidentity(1,1)primarykey,
Tnamevarchar(50),
Tageint,
Taddressvarchar(200),
)SQL控件用的是专用的驱动程序,能高效的访问SQLServer数据库
SQLConnection只能访问SQLServer,而OleDbConnection则可以访问所有数据库。
如果只是访问SQLServer的话,SQL比OleDb更快。
希望本文所述对大家的asp.net程序设计有所帮助。