2012-04-13 37 views
8

Estoy intentando leer un archivo de hoja de cálculo llamada Book1.xls que contiene una hoja de cálculo llamada Sheet1

Sin embargo estoy recibiendo el siguiente error:

The Microsoft Jet database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly.

Aquí hay un fragmento del código que estoy usando:

Dim dt As DataTable = New DataTable() 
Select Case fileExt 
    Case ".csv" 
     Dim reader As New CsvReader 
     dt = reader.GetDataTable(filePath) 
    Case ".xls", ".xlsx" 

     Dim oleDbConnStr As String 
     Select Case fileExt 
      Case ".xls" 
       oleDbConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filePath & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2""" 
      Case ".xlsx" 
       oleDbConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filePath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2""" 
     End Select 



     Using oleDbConn As OleDbConnection = New OleDbConnection(oleDbConnStr) 
      oleDbConn.Open() 

      Dim oleDbCmd As New OleDbCommand("SELECT * FROM [Sheet1$]", oleDbConn) 
      Dim oleDbDa As New OleDbDataAdapter(oleDbCmd) 
      oleDbDa.Fill(dt) 

      oleDbConn.Close() 
     End Using 



End Select 

no puedo entender por qué el código no puede encontrar mi hoja de trabajo. ¿Por qué es esto y cómo puedo resolverlo?

+0

intente una vez con la ruta de absoulte: origen de datos = C: \\ myexcel.xls; –

+0

@AshwiniVerma 'filepath' es la ruta absoluta porque uso' Server.MapPath() ' – Curt

+0

visite este enlace e intente obtener el nombre de la hoja mediante la programación: http://forums.asp.net/t/1751143.aspx/1 –

Respuesta

13

He encontrado el problema.

Parece que la hoja de cálculo se estaba guardando en la ubicación incorrecta, por lo que filepath no apuntaba a un archivo que existe.

No compré esto al principio porque asumí que aparecería un mensaje de error diferente. Algo como "Book1.xls no se pudo encontrar". Sin embargo, parece que si no existe, el mensaje simplemente indicará que no puede encontrar la Hoja de trabajo.

0
No

seguro, tengo algo de código similar (C#) que funciona bien ...

Tal vez usted puede detectar una diferencia?

string connectionString = string.Format(Thread.CurrentThread.CurrentCulture, "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;'", excelFilePath); 
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb"); 
using (DbConnection connection = factory.CreateConnection()) 
{ 
    connection.ConnectionString = connectionString; 
    using (DbCommand command = connection.CreateCommand()) 
    { 
     command.CommandText = @"SELECT [File], [ItemName], [ItemDescription], [Photographer name], [Date], [Environment site] FROM [Metadata$]"; 
     connection.Open(); 
     using (DbDataReader dr = command.ExecuteReader()) 
     { 
      if (dr.HasRows) 
      { 
       while (dr.Read()) 
       { 
        ....... 
       } 
      } 
     } 
     connection.Close(); 
    } 
} 

Intente cambiar el nombre de su hoja; o agregando columnas explícitamente; o verificar si es sensible a mayúsculas y minúsculas.

0

Cambie la ubicación de su archivo Excel, este error se resolverá. puede poner su archivo en la misma carpeta en su fuente presente

0

mejor solución a través vb codificado desde este enlace, todos los créditos a estas folks- http://www.vbforums.com/showthread.php?507099-data-from-excel-sheet-to-datagrid-(vb)

C# Mi solución esperada continuación

string connString = "Driver={Microsoft Excel Driver (*.xls)};READONLY=FALSE;DriverId=790;Dbq=" + "C:\\Users\\BHARAVI\\Documents\\visual studio 2013\\Projects\\ERP\\ERPAutomation\\Assets\\Data\\Data.xls"; 

OdbcConnection conn = new OdbcConnection(connString); 

conn.ConnectionTimeout = 500; 
OdbcCommand CMD = new OdbcCommand("SELECT * FROM [Sheet1$]", conn); 
OdbcDataAdapter myDataAdaptor = new OdbcDataAdapter(CMD); 
DataSet ds = new DataSet(); 
myDataAdaptor.Fill(ds ,"Sheet1"); 
DataTable dt = ds.Tables[0]; 
foreach (DataRow dr in dt.Rows) 
{ 
    loginId = dr["LoginId"].ToString(); 
    encryptedPassword = dr["PWD"].ToString(); 
    URL = dr["URL"].ToString(); 
} 
1

Además, asegúrese de que ya no tiene el archivo abierto en Excel. No podrá leer el archivo si está abierto en otro lugar. Tuve el mismo error y me di cuenta de que tenía el archivo abierto en Excel.

0

Si el nombre de archivo tiene carácter adicional de puntos, como a continuación:

sample.data.csv 

siguiente instrucción de selección:

SELECT * FROM [sample.data.csv] 

con cadena de conexión:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source="C:\Data\"; Extended Properties="text;HDR=Yes;Format=Delimited;"; 

fallará con excepción:

Additional information: The Microsoft Jet database engine could not find the object 'sample.data.csv'. Make sure the object exists and that you spell its name and the path name correctly. 
Cuestiones relacionadas