Невозможно прочитать данные из файла Excel 2007 - PullRequest
0 голосов
/ 29 марта 2012

Я пытаюсь импортировать данные из файла Excel (.xlsx) в базу данных sql, моя проблема в том, что я всегда получаю сообщение об ошибке «Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine», пожалуйста, обратите внимание, что перед тем, как сказать мне искать эту ошибку, прочитайте ниже:

  1. моя строка подключения выглядит следующим образом: string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelUploadLocation + fileName + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
  2. Я установил AccessDatabaseEngine.exe отсюда: http://www.microsoft.com/download/en/details.aspx?id=13255
  3. процесс работает на моем компьютере (32-битная Windows 7), но не работает на сервере (Windows Server 2008 R2 64-битная)
  4. Я не могу изменить целевую платформу с VS 2008 (с любого процессора на x86), как вы можете видеть на изображении ниже enter image description here

Любая помощь будет принята с благодарностью.

Ответы [ 3 ]

0 голосов
/ 29 марта 2012

Это должно сделать работу

          /// <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;            

        }
    }
0 голосов
/ 29 марта 2012

Попробуйте установить это http://www.microsoft.com/download/en/details.aspx?id=23734

0 голосов
/ 29 марта 2012

Вы всегда можете попробовать альтернативу (используя OfficeOpenXml)

Вот пример использования hot для добавления элементов столбца Excel 2007 в список с именем lista. Я полагаю, вы всегда можете легко добавить данные памяти в БД:

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)
                            {

                            }


                        }
                    }
                }
            }
        }
...