简体   繁体   English

无法从Excel 2007文件中读取数据

[英]Unable to read data from excel 2007 file

I am trying to import data from excel file (.xlsx) into sql database, my problem is that i am always getting the error "The ' Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine ", please note that before telling me to search for this error read the below: 我正在尝试将数据从excel文件(.xlsx)导入sql数据库,我的问题是我总是收到错误“ Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine ”,请注意在告诉我搜索此错误之前,请先阅读以下内容:

  1. my connection string is as follows: string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelUploadLocation + fileName + ";Extended Properties=\\"Excel 12.0 Xml;HDR=YES\\""; 我的连接字符串如下: string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelUploadLocation + fileName + ";Extended Properties=\\"Excel 12.0 Xml;HDR=YES\\"";
  2. I installed AccessDatabaseEngine.exe from here: http://www.microsoft.com/download/en/details.aspx?id=13255 我从这里安装了AccessDatabaseEngine.exe: http : //www.microsoft.com/download/en/details.aspx?id= 13255
  3. the process is working on my pc (windows 7 32 bit) but not working on the server (windows server 2008 R2 64bit) 该进程在我的PC上运行(Windows 7 32位),但在服务器上不运行(Windows Server 2008 R2 64bit)
  4. I can't change the target platform from VS 2008 (from any cpu to x86) as you can see in the image below 我无法从VS 2008(从任何cpu到x86)更改目标平台,如下图所示 在此处输入图片说明

Any help would be highly appreciated. 任何帮助将不胜感激。

This should do the work 这应该做的工作

          /// <summary>

    /// This method retrieves the excel sheet names from 

    /// an excel workbook & reads the excel file


    /// </summary>

    /// <param name="excelFile">The excel file.</param>

    /// <returns></returns>
    #region GetsAllTheSheetNames of An Excel File
    public static string[] ExcelSheetNames(String excelFile)
    {
        DataTable dt;
        string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFile + ";Extended Properties='Excel 12.0;HDR=Yes'";

        using (OleDbConnection objConn = new OleDbConnection(connString))
        {
            objConn.Open();
            dt =
            objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (dt == null)
            {
                return null;
            }
            string[] res = new string[dt.Rows.Count];
            for (int i = 0; i < res.Length; i++)
            {
                string name = dt.Rows[i]["TABLE_NAME"].ToString();
                if (name[0] == '\'')
                {
                    //numeric sheetnames get single quotes around
                    //remove them here
                    if (Regex.IsMatch(name, @"^'\d\w+\$'$"))
                    {
                        name = name.Substring(1, name.Length - 2);
                    }
                }
                res[i] = name;
            }
            return res;
        }
    }
    #endregion

/// ///

    /// This method retrieves the excel sheet specified and 
    /// gets the data from the required columns

    /// and inserts the required columns into database



    /// </summary>

    /// <param name="excelFile">The excel file.</param>

    /// <returns></returns>
    #region GetstheRequiredcolumns from the Specified sheet
    public static DataTable columnNamessheet1(String excelFile)
    {
        string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFile + ";Extended Properties='Excel 12.0;HDR=yes'";
        string connectionstring ="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DebitCare;Data Source=SSDEV7-HP\\SQLEXPRESS";

        using (OleDbConnection conn = new OleDbConnection(connString))
        {
            SqlConnection SqlConn1 = new SqlConnection(connectionstring);
            SqlConn1.Open();
            OleDbCommand odc = new OleDbCommand(string.Format("Select LoanNumber,CustomerName,DateofBirth,MobileNo,SanctionDate,EmployerName FROM [BAJAJ DUMP$]"), conn);
            conn.Open();
            OleDbDataReader reader = odc.ExecuteReader();               
            DataTable sheetSchema = reader.GetSchemaTable();
            SqlBulkCopy sqlbulk = new SqlBulkCopy(SqlConn1);
            sqlbulk.DestinationTableName = "CUSTOMER_DETAILS";
            sqlbulk.ColumnMappings.Add("LoanNumber", "CUSTOMER_LOAN_NO");
            sqlbulk.ColumnMappings.Add("CustomerName", "CUSTOMER_ NAME");
            sqlbulk.ColumnMappings.Add("DateofBirth", "CUSTOMER_DOB");
            sqlbulk.ColumnMappings.Add("MobileNo", "CUSTOMER_MOBILE NUMBER");
            sqlbulk.ColumnMappings.Add("SanctionDate", "CUSTOMER_SANCTION DATE");
            sqlbulk.ColumnMappings.Add("EmployerName", "CUSTOMER_COMPANY NAME");
            sqlbulk.WriteToServer(reader);
            conn.Close();
            return sheetSchema;            

        }
    }

You can always try alternative(using OfficeOpenXml ) 您可以随时尝试替代方法(使用OfficeOpenXml

Here is the example of use hot to add Excel 2007 column elements into a list called lista . 这是使用hot将Excel 2007列元素添加到名为lista的列表中的示例。 I suppose you can always easily add memory data into DB : 我想您总是可以轻松地将内存数据添加到DB中:

using OfficeOpenXml;
 using (var excelPackage = new ExcelPackage(fi))
        {
            ExcelWorkbook workbook = excelPackage.Workbook;
            if (workbook != null)
            {
                if (workbook.Worksheets.Count > 0)
                {
                    ExcelWorksheet worksheet = workbook.Worksheets.Single(a => a.Name == sheetname);
                    for (int i = row; i < worksheet.Dimension.End.Row; i++)
                    {
                        if (worksheet.Cells[i, column].Value != null)
                        {
                            try
                            {
                                double s = double.Parse(worksheet.Cells[i, column].Value.ToString());
                                lista.Add(s);
                            }
                            catch (FormatException)
                            {

                            }


                        }
                    }
                }
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM