.net 将Excel文件导入数据库

代码以及遇到的问题:

(1)前台页面:

 选择Excel文件:

 
                   
                   

(2)后端代码:

 #region Excel导入数据库
    protected void BtnImport_Click(object sender, EventArgs e)
    {
        #region
        string mes = string.Empty;
        string fileName = string.Empty;
        try
        {
            int code = UpLoadXls(FileExcel, out fileName);//上传Excel文件
            if (String.IsNullOrEmpty(fileName))
            {
                divmes.InnerHtml = "请先上传Excel文件";
                return;
            }

          
  int retCode = ImportExcelToData(fileName);//将Excel导入数据库     
            if (retCode > 0)
            {
                mes = "导入成功!";
            }
            else
            {
                #region 错误提示

                switch (retCode)
                {
                    case -1:
                        mes = "异常错误!";
                        break;
                    case -2:
                        mes = "Excel格式错误!";
                        break;
                    case -3:
                        mes = "导入数据为空!";
                        break;
                    default:
                        mes = "异常错误!";
                        break;
                }
                #endregion
            }
            //删除上传的XLS文件
            if (!String.IsNullOrEmpty(fileName) && System.IO.File.Exists(fileName))
            {
                System.IO.File.Delete(fileName);
            }
        }
        catch
        {
            mes = "导入失败!";
        }
        divmes.InnerHtml = mes;
        #endregion
    }

    ///


    /// 上传Excel文件
    ///

    /// 上传的控件名
    ///
    public int UpLoadXls(System.Web.UI.HtmlControls.HtmlInputFile inputfile, out string lastFileName)
    {
        #region
        int code = 0;
        lastFileName = string.Empty;
        string uploadfilepath = string.Empty;
        string newFileName = string.Empty;
        string fileExtend = "";

        try
        {
            if (!String.IsNullOrEmpty(inputfile.Value))
            {
                int fileSize = inputfile.PostedFile.ContentLength;
                if (fileSize == 0)
                {
                    code = -1;//导入的Excel文件大小为0,请检查是否正确!
                }

                #region 获取扩展名
                int isTrue = 0;
                List listExtend = new List();
                listExtend.Add("xls");
                listExtend.Add("xlsx");
                fileExtend = FileHelper.GetFileExtension(inputfile.Value);
                foreach (var ext in listExtend)
                {
                    if (fileExtend.ToLower() == ext)
                    {
                        isTrue = 1;
                        break;
                    }
                }
                if (isTrue == 0)
                {
                    code = -2;//你选择的文件格式不正确,只能导入EXCEL文件!
                }
                #endregion

                #region 上传excel
                //新文件名
                newFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileExtend;
                //路径
                uploadfilepath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\Upload\\AdservingExel\\";
                //判断是否有该目录
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(uploadfilepath);
                if (!dir.Exists)
                {
                    dir.Create();
                }
                lastFileName = uploadfilepath + "\\" + newFileName;
                //如果文件存在,删除文件
                if (File.Exists(lastFileName))
                {
                    File.Delete(lastFileName);
                }
                // 上传文件
                inputfile.PostedFile.SaveAs(lastFileName);
                if (!String.IsNullOrEmpty(lastFileName))
                {
                    code = 1;
                }
                else
                {
                    code = -1;
                }
                #endregion
            }
            else
            {
                code = -3;//请选择要导入的Excel文件!
            }
        }
        catch
        {
            code = 0;
        }
        return code;
        #endregion
    }

    //读取Excel数据
    public int ImportExcelToData(string fileName)
    {
        #region
        int code = 0;
        try
        {
            string oleDBConnString = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + fileName + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
            if (fileName.Contains("xls") || fileName.Contains("xlsx"))
            {
                #region 读取
                oleDBConnString = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + fileName + ";Extended Properties='Excel 12.0; HDR=YES; IMEX=1'";
                OleDbConnection oleDBConn = null;
                OleDbDataAdapter oleAdMaster = null;
                DataTable m_tableName = new DataTable();
                DataSet ds = new DataSet();
                oleDBConn = new OleDbConnection(oleDBConnString);
                oleDBConn.Open();
                m_tableName = oleDBConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });

                if (m_tableName != null && m_tableName.Rows.Count > 0)
                {
                    m_tableName.TableName = m_tableName.Rows[0]["TABLE_NAME"].ToString();
                }
                string sqlMaster;
                sqlMaster = " SELECT *  FROM [" + m_tableName.TableName + "]";
                oleAdMaster = new OleDbDataAdapter(sqlMaster, oleDBConn);
                oleAdMaster.Fill(ds, "m_tableName");
                oleAdMaster.Dispose();
                oleDBConn.Close();
                oleDBConn.Dispose();

                #endregion

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    code = AddDatasetToSQL(ds, 9);
                }
            }
        }
        catch
        {
            code = -1;
        }
        return code;
        #endregion
    }
    ///
    /// 将Dataset的数据导入数据库
    ///

    /// 数据集
    /// 数据集列数
    ///
    private int AddDatasetToSQL(DataSet pds, int Cols)
    {
        #region
        int code = 0;
        int columnsCount, rowsCount;
        try
        {
            columnsCount = pds.Tables[0].Columns.Count;
            if (columnsCount < Cols)
            {
                code = -2;
            }
            rowsCount = pds.Tables[0].Rows.Count;
            if (pds != null && rowsCount > 0)
            {
                DataTable dtData = pds.Tables[0];
                for (int i = 0; i < dtData.Rows.Count; i++)
                {
                    #region 导入数据
                    try
                    {
                          //加入数据库代码
                    }
                    catch
                    {
                        continue;
                    }
                    #endregion
                }
                code = 1;
            }
            else
            {
                code = -3;//导入数据为空
            }
        }
        catch
        {
            code = -1;
        }
        return code;
        #endregion
    }
    #endregion


(3)其中遇到问题:

(1)如果遇到“未在本地计算机上注册Microsoft.ACE.OLEDB.12.0提供程序”这种异常:
解决办法:
第一种方法:在对应的 IIS 应用程序池中,“设置应用程序池默认属性”右击/“高级设置”/"启用32位应用程序",设置为 true。
第二种方法:确保安装了Microsoft.ACE.OLEDB.12.0驱动

http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/AccessDatabaseEngine.exe

第三种方法:在vs中右击项目--》属性--》生成 下的 目标平台 改为x86

.Microsoft.Jet.OLEDB.4.0在64位系统上不支持,需要修改架构,从x64改为x86,无论是WinForm还是ASP.NET;

或者修改连接字符串为Microsoft.ACE.OLEDB.12.0并且安装AccessDatabaseEngine x64数据访问组件;


(2)如果遇到“导入excel错误:外部表不是预期的格式“ 解决方案:

在asp.net网站中导出Excel文件后,再把文件导入到数据库中。 读取Excel文件时,打开连接出错。

错误为:外部表不是预期的格式

解决:检查了一下,导出的Excel是标准文件不是html,没错,Excel文件正常。 

  调试代码,创建连接对象oleDbConnection也正常,但在conn.Open()打开链接时出错。 

仔细看了下链接字符串,检查出了错误,Excel版本问题,Exce连接字符串版本是office2003的 ,更改为Excel2007版本则正常导入。 

(3).csv格式数据文件导入数据库出现问题:

这段出错,'G:\zxb\test\Test\create20091225.csv'不是一个有效的路径。 确定路径名称拼写是否正确,以及是否连接到文件存放的服务器。

解决办法:

将filepath改为:
Directory.GetParent(filepath)




你可能感兴趣的:(.net开发,.net,excel)