Visualizzazione dei risultati da 1 a 8 su 8
  1. #1
    Utente di HTML.it
    Registrato dal
    Mar 2010
    Messaggi
    24

    C# e lettura singola cella excel

    Sto cercando di fare una cosa che probabilmente per molti di voi sarà semplice ma non riesco a fare...ho cercato molto nel forum ma.......

    Si tratta di leggere un singolo valore in una cella ben precisa di un excel e metterlo su una variabile o su un textbox....senza dataset o altro...poi lo passerò ad un database
    Ho provato in questo modo ma non funziona...

    codice:
     string pathfile = txtPath.Text;
                string ExcelconnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathfile + ";Extended Properties=\"Excel 8.0;\"";
                OleDbConnection ExcelConnection = new OleDbConnection(ExcelconnectionString);
                string strSheetname = "Dettaglio OSSIDI-LAMINATOI";
                string strSheetRange="C5";
                string ExcelQuery="SELECT * FROM ["+strSheetname+"$"+strSheetRange+":"+strSheetRange+"]";
                OleDbCommand ExcelCommand = new OleDbCommand(ExcelQuery, ExcelConnection);
                ExcelCommand.Connection.Open();
                
                OleDbDataReader ExcelmyReader = ExcelCommand.ExecuteReader();
                String risulato = Convert.ToString(ExcelmyReader[0]);
    Ma l'errore che ottengo è.....
    Nessun dato esistente per la riga/colonna.

  2. #2
    Utente di HTML.it L'avatar di gibra
    Registrato dal
    Apr 2008
    residenza
    Italy
    Messaggi
    4,244
    per ottenere un singolo valore dovresti usare ExecuteScalar.
    http://msdn.microsoft.com/it-it/libr...utescalar.aspx

    ExecuteReader restituisce righe, non celle.

  3. #3
    Utente di HTML.it
    Registrato dal
    Mar 2010
    Messaggi
    24
    Ci sto provando eh...non ho mica mollato...è che ho un errore "Impossibile trovare ISAM installabile"...sono qui che provo a registrare dll come indicato su alcuni siti..

  4. #4
    Utente di HTML.it L'avatar di gibra
    Registrato dal
    Apr 2008
    residenza
    Italy
    Messaggi
    4,244
    Evidentemente sbagli qualcosa.
    Non ci sono DLL da registrare, lascia perdere...

    Studiati questo progetto, invece:

    http://nuke.vbcorner.net/Progetti/NE...T/Default.aspx



  5. #5
    Utente di HTML.it
    Registrato dal
    Mar 2010
    Messaggi
    24
    Allora ho guardato bene il tuo progetto...
    Sto cercando di non copiare papale papale ma di imparare infatti se poi comincio a usare questa applicazione devo anche essere in grado di metterci le mani nel caso in cui si incastri qualcosa....
    per questo motivo ho pensato di provare a fare la stessa cosa che fai nel progetto ma in C# e per il momento senza Early-late binding (una cosa per volta)...

    Ora però ho due problemi che mi impediscono la compilazione (non so sto pensando di rifare da zero una macchina da tenere solo ed esclusivamente per lo sviluppo...in questa ci ho installato/disintallato troppe cose...)

    codice:
     Excel.Application ExcelApp = new Excel.Application();
                Excel.Workbook ExcelWorkbook = new Excel.Workbook();
                Excel.Worksheet ExcelWorksheet = new Excel.Worksheet();
                //Excel.Range ExcelRange = new Excel.Range();
    
                //Apro la finestra di dialogo per la selezione del file
                OpenFileDialog ApriFile = new OpenFileDialog();
                string fileName = ApriFile.FileName;
                ExcelWorkbook = ExcelApp.Workbooks.Open(fileName);
                string ExcelconnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=Excel 8.0;HDR=No";
                OleDbConnection ExcelConnection = new OleDbConnection(ExcelconnectionString);
                //Apro la connessione
                string strSheetname = "Dettaglio OSSIDI-LAMINATOI";
                string strSheetRange = "C5";
                string ExcelQuery = "SELECT * FROM [" + strSheetname + "$" + strSheetRange + ":" + strSheetRange + "]";
                ExcelConnection.Open();
                OleDbDataAdapter cmd = new OleDbDataAdapter(ExcelQuery,ExcelConnection);
                //OleDbCommand ExcelCommand = new OleDbCommand(ExcelQuery, ExcelConnection);
                //ExcelCommand.Connection.Open();
                DataSet DS = new DataSet();
                cmd.Fill(DS, "tabella");
                ExcelConnection.Close();
    Il primo problema è che se non commento la riga

    Excel.Range ExcelRange = new Excel.Range();

    non mi fa proprio compilare perchè mi da errore
    "Impossibile creare un'istanza della classe o dell'interfaccia astratta 'Microsoft.Office.Interop.Excel.Range'
    e non capisco perchè

    Quindi dopo aver commentato compilo ma alla riga

    Excel.Workbook ExcelWorkbook = new Excel.Workbook();

    compare un errore



    System.Runtime.InteropServices.COMException non è stata gestita
    Message=Recupero della class factory COM per il componente con CLSID {00020819-0000-0000-C000-000000000046} non riuscito a causa del seguente errore: 80040154 Interfaccia non registrata. (Eccezione da HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
    Source=mscorlib
    ErrorCode=-2147221164
    StackTrace:
    in System.Runtime.Remoting.RemotingServices.AllocateU ninitializedObject(RuntimeType objectType)
    in System.Runtime.Remoting.Activation.ActivationServi ces.CreateInstance(RuntimeType serverType)
    in System.Runtime.Remoting.Activation.ActivationServi ces.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj)
    in System.RuntimeTypeHandle.CreateInstance(RuntimeTyp e type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
    in System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
    in System.RuntimeType.CreateInstanceDefaultCtor(Boole an publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
    in System.Activator.CreateInstance(Type type, Boolean nonPublic)
    in System.Activator.CreateInstance(Type type)
    in ProvaForm.Form1.btnCarica_Click(Object sender, EventArgs e) in D:\Documents\Visual Studio 2010\ProvaForm\ProvaForm\Form1.cs:riga 84
    in System.Windows.Forms.Control.OnClick(EventArgs e)
    in System.Windows.Forms.Button.OnClick(EventArgs e)
    in System.Windows.Forms.Button.OnMouseUp(MouseEventAr gs mevent)
    in System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
    in System.Windows.Forms.Control.WndProc(Message& m)
    in System.Windows.Forms.ButtonBase.WndProc(Message& m)
    in System.Windows.Forms.Button.WndProc(Message& m)
    in System.Windows.Forms.Control.ControlNativeWindow.O nMessage(Message& m)
    in System.Windows.Forms.Control.ControlNativeWindow.W ndProc(Message& m)
    in System.Windows.Forms.NativeWindow.DebuggableCallba ck(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
    in System.Windows.Forms.UnsafeNativeMethods.DispatchM essageW(MSG& msg)
    in System.Windows.Forms.Application.ComponentManager. System.Windows.Forms.UnsafeNativeMethods.IMsoCompo nentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
    in System.Windows.Forms.Application.ThreadContext.Run MessageLoopInner(Int32 reason, ApplicationContext context)
    in System.Windows.Forms.Application.ThreadContext.Run MessageLoop(Int32 reason, ApplicationContext context)
    in System.Windows.Forms.Application.Run(Form mainForm)
    in ProvaForm.Program.Main() in D:\Documents\Visual Studio 2010\ProvaForm\ProvaForm\Program.cs:riga 18
    in System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
    in System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
    in System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
    in System.Runtime.Hosting.ManifestRunner.ExecuteAsAss embly()
    in System.Runtime.Hosting.ApplicationActivator.Create Instance(ActivationContext activationContext, String[] activationCustomData)
    in System.Runtime.Hosting.ApplicationActivator.Create Instance(ActivationContext activationContext)
    in System.Activator.CreateInstance(ActivationContext activationContext)
    in Microsoft.VisualStudio.HostingProcess.HostProc.Run UsersAssemblyDebugInZone()
    in System.Threading.ThreadHelper.ThreadStart_Context( Object state)
    in System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
    in System.Threading.ExecutionContext.Run(ExecutionCon text executionContext, ContextCallback callback, Object state)
    in System.Threading.ThreadHelper.ThreadStart()
    InnerException:

  6. #6
    Utente di HTML.it L'avatar di gibra
    Registrato dal
    Apr 2008
    residenza
    Italy
    Messaggi
    4,244
    Ti avevo già indicato che devi usare ExecuteScalar()
    quindi dovrai usare un OleDbCommand (e NON un OleDbDataAdapter).

    e da
    ";Extended Properties=Excel 8.0;HDR=No";

    elimina

    ;HDR=No

    Excel.Range ExcelRange = new Excel.Range();
    non serve a niente.

  7. #7
    Utente di HTML.it
    Registrato dal
    Mar 2010
    Messaggi
    24
    Ok...per l'OleDbDataAdapter lo avevo messo perchè mi stavo convertendo ad usare il DataSet.....
    ok ora modifico HDR...

    ok che Excel.Range ExcelRange = new Excel.Range(); non serve a niente ma non capisco come mai mi da errore...

    Mi rimane l'errore di compilazione alla riga...

    Excel.Workbook ExcelWorkbook = new Excel.Workbook();

    ...ora faccio un pò di tentativi

  8. #8
    Utente di HTML.it
    Registrato dal
    Mar 2010
    Messaggi
    24
    L'applicazione comincia a funzionare...ora riesco a leggere l'excel e a fare l'insert nell'access....
    Però no vorrei che interpretasse la prima riga come nome delle colonne..

    Mettendo nella stringa di connessione
    con = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLED B.4.0;" & "Data Source=" & fileExcel & ";" & "Extended Properties=Excel 8.0; FirstRowHasNames=No")

    oppure
    con = New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLED B.4.0;" & "Data Source=" & fileExcel & ";" & "Extended Properties=Excel 8.0; HDR=No")

    All'apertura della connessione mi da errore "Impossibile trovare ISAM installabile".
    Togliendo FirstRowHasNames o HDR tutto funziona regolarmente ma mi interpreta la prima riga come nomi delle colonne..

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.