asp.net中EXCEL数据导入到数据库的方法

所属分类: 网络编程 / ASP.NET 阅读数: 725
收藏 0 赞 0 分享

本文实例讲述了asp.net中EXCEL数据导入到数据库的方法。分享给大家供大家参考。具体分析如下:

excel是办公中非常常用的一个办公表格了,但我们在开发中通常会需要直接把excel数据快速导入到数据库中了,这里整理了一个asp.net中EXCEL数据导入到数据库的例子供各位参考学习。

注意:EXCEL中的第一行不能导入。
下面是源码:IntoExcel.aspx:

复制代码 代码如下:
<%@ Page  AutoEventWireup="true" CodeFile="IntoExcel.aspx.cs" Inherits="study_IntoExcel" %> 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" > 
<head id="Head1" runat="server"> 
<title>无标题页</title> 
<script language="javascript" type="text/javascript"><!-- 
// <!CDATA[ 
function check() { 
var k=//S+/.[xls]/; 
if(!k.test(document.getElementById("fileId").value)) 

    alert("只能上次xls格式的文件"); 
    return false; 

return true; 

// --></script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
    <p> 
        <asp:FileUpload ID="fileId" runat="server" /> 
        <asp:Button ID="Button1" runat="server" Text="上传" OnClientClick="return check()" onclick="Button1_Click" /></p> 
    </div> 
    </form> 
</body> 
</html>

IntoExcel.aspx.cs
复制代码 代码如下:
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Collections; 
using System.Configuration; 
using System.Data; 
using System.Web.Security; 
using System.Web.UI.HtmlControls; 
using System.Web.UI.WebControls.WebParts; 
using System.IO; 
using System.Data.OleDb; 
using System.Data.SqlClient; 
using System.Web.UI.WebControls; 
 
public partial class study_IntoExcel : System.Web.UI.Page 

    protected void Page_Load(object sender, EventArgs e) 
    { 
 
    } 
        /// <summary> 
        /// 上传文件 
        /// </summary> 
        /// <param name="sender"></param> 
        /// <param name="e"></param> 
        protected void Button1_Click(object sender, EventArgs e) 
        { 
            string fileName = fileId.FileName; 
            string savePath = Server.MapPath("~/file/"); 
            FileOperatpr(fileName, savePath); 
            fileId.SaveAs(savePath + fileName); 
            DataOperator(fileName, savePath); 
        } 
        /// <summary> 
        /// 数据操作 
        /// </summary> 
        /// <param name="fileName"></param> 
        /// <param name="savePath"></param> 
        private void DataOperator(string fileName, string savePath) 
        { 
            string myString = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =  " + savePath + fileName + ";Extended Properties=Excel 8.0"; 
            OleDbConnection oconn = new OleDbConnection(myString); 
            oconn.Open(); 
            DataSet ds = new DataSet(); 
            OleDbDataAdapter oda = new OleDbDataAdapter("select * from [Sheet1$]", oconn); 
            oda.Fill(ds); 
            oconn.Close(); 
            DataSetOperator(ds,savePath+fileName); 
        } 
        /// <summary> 
        /// 数据集操作 
        /// </summary> 
        /// <param name="ds"></param> 
        private void DataSetOperator(DataSet ds,string filePath) 
        { 
            SqlConnection conn = new SqlConnection("Data Source=SONYSVR;Initial Catalog=IAR_Factory_811;User ID=sa;Password=P@ssword"); 
            conn.Open(); 
            SqlTransaction str = conn.BeginTransaction();//利用事务处理 防止中断 
            int k = 0; 
            if (ds.Tables[0].Rows.Count < 1) 
            { 
                Response.Write("<script>alert('没有数据!')</script>"); 
                return; 
            } 
            try 
            { 
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
                { 
                    string <strong><a href="https://www.jb51.net" title="sql" target="_blank">sql</a></strong>Str = "insert into IntoExcel(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()+"')"; 
                    SqlCommand cmd = new SqlCommand(sqlStr, conn, str); 
                    cmd.Transaction = str; 
                    k += cmd.ExecuteNonQuery(); 
                } 
                str.Commit(); 
            } 
            catch (Exception ex) 
            { 
                Response.Write("发生异常,数据已回滚/n信息/n" + ex.Message); 
                str.Rollback(); 
            } 
            finally 
            { 
                Response.Write("上传成功" + k + "条"); 
                File.Delete(filePath); 
            } 
        } 
        /// <summary> 
        /// 文件操作 
        /// </summary> 
        /// <param name="fileName"></param> 
        /// <param name="savePath"></param> 
        private void FileOperatpr(string fileName, string savePath) 
        { 
            if (!Directory.Exists(savePath)) 
            { 
                Directory.CreateDirectory(savePath); 
            } 
            if (File.Exists(savePath + fileName)) 
            { 
                File.Delete(savePath + fileName); 
            } 
        } 

 
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + savePath + ";Extended Properties='Excel 8.0;HDR=YES
 Provider=Microsoft.Jet.OLEDB.4.0;;//连接驱动
Data Source=" + savePath + "; // 数据库地址
Extended Properties='Excel 8.0; // 连接的是Excel8.0
HDR=YES;// 有两个值:YES/ NO, 这2个值,说了你是否能直接读列名,NO,只可以读下标
IMEX=1;//解决数字与字符混合时,识别不正常的情况.

这个读入数据库的方式不是最佳的,应该用office组件
select * from [Sheet1$] //引用EXCLE文件中sheet1工作表的内容
OleDB控件用的是OleDb的驱动程序,可以访问各种数据库  
 
数据库中的字段:
复制代码 代码如下:
create table IntoExcel 

    Tid int identity(1,1) primary key, 
    Tname varchar(50), 
    Tage int, 
    Taddress varchar(200), 
     
)

SQL控件用的是专用的驱动程序,能高效的访问SQL Server数据库
SQLConnection只能访问SQL Server,而OleDbConnection则可以访问所有数据库。  
如果只是访问SQL Server的话,SQL比OleDb更快。

希望本文所述对大家的asp.net程序设计有所帮助。

更多精彩内容其他人还在看

asp.net 页面间传值与跳转的区别

通过Server.Transfer("b.aspx") 与Response.Redirect("b.aspx")的区别
收藏 0 赞 0 分享

ASP.NET Gridview与checkbox全选、全不选实现代码

ASP.NET Gridview checkbox全选与全不选实现代码,其实原理就是利用js来实现的,但需要简单的设置下回传。
收藏 0 赞 0 分享

ASP.NET DropDownList控件的使用方法

ASP.NET DropDownList控件的使用方法,学习asp.net的朋友没用过这个控件的朋友可以参考下。
收藏 0 赞 0 分享

一些.NET对多线程异常处理技巧分享

多线程应用,在实际的项目或产品开发中,原则上来说,应该尽量避免,但是在强调用户体验的要求下或开发平台的限制下(如 Silverlight Socket 通讯),我们不得不用多线程。
收藏 0 赞 0 分享

ASP.NET MVC运行出现Uncaught TypeError: Cannot set property __MVC_FormValidation of null的解决方法

同一相站点,有些页面的客户端验证能工作,而有些死活不行。打开页面就出现Uncaught TypeError: Cannot set property __MVC_FormValidation of null错误
收藏 0 赞 0 分享

asp.net 通用分页显示辅助类(改进版)

在使用ASP.NET编程时,如果不用控件的默认分页功能,想自己搞一个,可以看看本文的asp.net通用分页显示辅助类哦。
收藏 0 赞 0 分享

微软 Visual Studio 2010官方下载地址给大家

昨天VS2010在网上报道都已经发布了,现在今天在网上找到Visual Studio 2010官方下载地址,提供给大家下载。
收藏 0 赞 0 分享

Javascript 直接调用服务器C#代码 ASP.NET Ajax实例

近来总有一些朋友会问到一些入门的问题,把这些问题整理一下,写出来。在以前的文章里,曾经利用纯JS编写过Ajax引擎,在真正开发的时候,大家都不喜欢以这种低效率的方式开发,利用MS Ajax的集成的引擎,可以简单不少工作。
收藏 0 赞 0 分享

ASP.NET 页面刷新的实现方法(包括html,js)

ASP.NET 页面刷新的实现方法,比较全了, 包括html与js下的实现方法。
收藏 0 赞 0 分享

asp.net 无刷新翻页就是这么简单

前两天看了一个自定义分页控件,和AspNetPager一样是实现IPostBackEventHandler接口,不过简洁许多,就想能不能实现ICallbackEventHandler接口做到无刷新分页呢?想到了就马上去做,终于,设想变成了现实!!
收藏 0 赞 0 分享
查看更多