ASP.NET实现Excel导入SQL数据库以及各种出现的问题解决方案

这两天想实现Excel导入数据库的功能,于是自己百度,简单做了个小Demo,环境:office2010,VS2008,win7,SQL2005;大体思路是如下这种方式:

1.利用操作Excel语句,取得Excel的数据。
2.将取得的数据封装在DataSet中
3.循环上面的DataSet,然后将表中的内容,依次插入到对应表中。

下面是代码的基本实现方式:

前台实现:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ImportDemo._Default" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        选择导入文件:<asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button runat = "server" ID = "btnImpot" Text = "导入" onclick="btnImpot_Click" />
    </div>
    </form>
</body>
</html>

后台:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;

namespace ImportDemo
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnImpot_Click(object sender, EventArgs e)
        {
            //是否含有文件
            if (!this.FileUpload1.HasFile)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('请选择导入的Excel表!');</script>");
                return;
            }
            //判断导入文件是否正确
            string Extension = System.IO.Path.GetExtension(this.FileUpload1.FileName).ToString().ToLower();
            if (Extension != ".xls" && Extension !=".xlsx")
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('您导入的Excel文件不正确,请确认后重试!');</script>");
                return;
            }
            //拼接服务器文件名
            string FileName = DateTime.Now.ToString("yyyyMMddhhmmssmmmm") + this.FileUpload1.FileName;
            //保存路径
            string savePath = Server.MapPath("Excel/") + FileName;
            //将文件保存到服务器上
            FileUpload1.SaveAs(savePath);

            //将Excel中的数据放到DataTable中
            DataTable dt = GetExcelSheet(savePath, FileName);
            //向数据库中插入数据
            int i =  InsetData(dt);

            //提示导入成功数据
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('成功导入"+i+"条数据!');</script>");
        }
        /// <summary>
        /// 将Excel中的数据放到DataTable中
        /// </summary>
        /// <param name="strFileName">路径</param>
        /// <param name="strFileName">表名</param>
        /// <returns>DataTable数据</returns>
        public DataTable GetExcelSheet(string fileUrl,string table)
        {
            //office2007之前 仅支持.xls
            //const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=1';";
            //支持.xls和.xlsx,即包括office2010等版本的   HDR=Yes代表第一行是标题,不是数据;
            const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
            
            DataTable dt = null;
            //建立连接
            OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));
            try
            {
                //打开连接
                if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }

                
                DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                //获取Excel的第一个Sheet名称
                string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();

                //查询sheet中的数据
                string strSql = "select * from [" + sheetName + "]";
                OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);
                DataSet ds = new DataSet();
                da.Fill(ds,table);
                dt = ds.Tables[0];

                return dt;
            }
            catch (Exception exc)
            {
                throw exc;
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }
        /// <summary>
        /// 向数据库插入数据
        /// </summary>
        /// <param name="dt">Excel中的DataTable数据</param>
        public int InsetData(DataTable dt)
        {
            int i =0;
            foreach (DataRow item in dt.Rows)
            {
                Person per = new Person();
                per.Name = item["Name"].ToString();
                per.Age = Convert.ToInt32( item["Age"].ToString());
                per.Address = item["Address"].ToString();
                per.Phone = item["Phone"].ToString();

                if (DBHelper.Add(per) == 1)
                {
                    i++;
                }
            }
            return i;
        }
    }

    public class Person
    {
        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 年龄
        /// </summary>
        public int Age { get; set; }
        /// <summary>
        /// 地址
        /// </summary>
        public string Address { get; set; }
        /// <summary>
        /// 电话
        /// </summary>
        public string Phone { get; set; }
    }
}

之间新建了两个类:DBHelper 类(用于操作数据库的增删查改) 和 SqlConn 类(获得数据库连接字符串)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ImportDemo
{
    public class SqlConn
    {
        /// <summary>
        /// 获得连接字符串
        /// </summary>
        public static string ConnText
        {
            get { return System.Configuration.ConfigurationManager.ConnectionStrings["DbLink"].ConnectionString; ; }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;

namespace ImportDemo
{
    public class DBHelper
    {
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="per">人员类</param>
        /// <returns>成功返回1,否则返回0</returns>
        public static int Add(Person per)
        {
            int count = 0;
            string cmdText = "insert into Person(Name,Age,Address,Phone) values(@Name,@Age,@Address,@Phone)";
            SqlConnection conn = new SqlConnection(SqlConn.ConnText);
            try
            {
                //打开连接
                if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }

                SqlCommand cmd = new SqlCommand(cmdText, conn);
                SqlParameter[] sqlparas = { new SqlParameter("@Name",per.Name),
                                          new  SqlParameter("@Age",per.Age),
                                          new SqlParameter("@Address",per.Address),
                                          new SqlParameter("@Phone",per.Phone)
                                          };
                cmd.Parameters.AddRange(sqlparas);

                count =  cmd.ExecuteNonQuery();
                
            }
            catch (Exception exc)
            {
                throw exc;
            }
            finally
            {
                conn.Close();
            }
            return count;
        }
    }
}

在Web.config中添加连接数据库的字符串:

<connectionStrings>
        <add name="DbLink" connectionString="Data Source=.\SQL2005;Initial Catalog=ceshi;User Id=sa;Password=123; "/>
    </connectionStrings>

以上就是全部的代码。

当然在这之中也有几点需要注意的地方:

1.导入时,报错:导入的表不是预期格式。
   原因:① Excel表的数据格式不正确。
      解决:修改Excel表的数据格式。
    
     ②.获得Excel数据的语句不正确。
      解决:如果是office2007之前,可以用这种方式:     
//office2007之前 仅支持.xls     const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=1';";       如果是2010的,用如下这种方式:     //支持.xls和.xlsx,即包括office2010等版本的 HDR=Yes代表第一行是标题,不是数据; const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
2.打开某某数据库失败。
  原因:数据库链接字符串出现错误。
    解决:修改Web.config文件中的连接字符串,将数据库对象改成自己的对应数据库名,用户名和密码。

作者:枫上善若水
出处:http://www.cnblogs.com/xilipu31/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
正在看本人博客的这位童鞋,我看你气度不凡,谈吐间隐隐有王者之气,日后必有一番作为!旁边有“推荐”二字,你就顺手把它点了吧,相得准,我分文不收;相不准,你也好回来找我!
原文地址:https://www.cnblogs.com/xilipu31/p/2859679.html