2014-12-18 15 views
16

Ho difficoltà a cercare di inserire righe in un oggetto tabella esistente. Qui è il mio frammento di codice:Come inserire le righe nell'oggetto tabella all'interno di un foglio Excel?

string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + @"C:\myExcelFile.xlsx" + ";Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=Yes;\""; 
using (OleDbConnection conn = new OleDbConnection(connectionString)) 
{ 
    conn.Open(); 
    OleDbCommand cmd = new OleDbCommand(); 
    cmd.Connection = conn; 

    string insertQuery = String.Format("Insert into [{0}$] (ID, Title,NTV_DB, Type) values(7959, 8,'e','Type1')", TabDisplayName); 
    cmd.CommandText = insertQuery; 
    cmd.ExecuteNonQuery(); 
    cmd = null; 
    conn.Close(); 
} 

Di conseguenza ho la mia righe inserite sotto un oggetto tabella ready-made:

enter image description here

Ho anche provato dati inserimento all'interno di un oggetto tavolo come così:

string insertQuery = String.Format("Insert into [{0}$].[MyTable] (ID, Title,NTV_DB, Type) values(7959, 8,'e','Type1')", TabDisplayName); 

Ma ottengo un errore:

The Microsoft Access database engine could not find the object 'MyTable'. Make sure the object exists and that you spell its name and the path name correctly. If 'MyTable' is not a local object, check your network connection or contact the server administrator.

Come si può vedere, la tabella con un nome MyTable esiste. Sarei molto grato se qualcuno potesse far luce su questo mistero.

enter image description here

+0

Ho modificato il tuo titolo. Per favore vedi, "[Le domande dovrebbero includere" tag "nei loro titoli?] (Http://meta.stackexchange.com/questions/19190/)", dove il consenso è "no, non dovrebbero". –

+0

La tabella ha sempre righe vuote alla fine? – peege

+0

Il nome della tabella non ha uno spazio alla fine del nome come "MyTable"? Solo un pensiero ... –

risposta

3

Sulla base here:

ADO.NET cannot access XL's Table objects (aka Lists) nor can it access range names that directly or indirectly reference the table's name or structured references. ADO.NET can access named ranges over tables that reference the table's cell range.

Esempio: Nome MyTable si riferisce a =$A$1:$E$3. Quindi è possibile utilizzare Range ad esempio (Sheet1$A:E) per questo scopo. In questo caso la sua dichiarazione di inserimento potrebbe cambiare a qualcosa di simile:

string insertQuery = "INSERT INTO [Sheet1$A:E] (ID, Title,NTV_DB, Type) VALUES (7959, 8,'e','Type1')"; 

Altre restrizioni:

Workbook Protection: ADO cannot access password protected workbooks.

Used Rows: ADO will insert below the last used row. NOTE! The last used row can be empty.

E Tables come già detto.

-2

Non sono sicuro di accesso C# funziona lo stesso di Excel, ma questo ha lavorato su un foglio di calcolo per me. Forse potrebbe aiutarti?

Table3.ListRows[1].Range.Insert(Excel.XlInsertShiftDirection.xlShiftDown); 
+0

La domanda richiede una soluzione ADO.NET –

3

Se si esegue questo codice:

var contents = new DataTable(); 
using (OleDbDataAdapter adapter = new OleDbDataAdapter(string.Format("Select * From [{0}$]", TabDisplayName), conn)) 
{ 
    adapter.Fill(contents); 
} 
Console.WriteLine(contents.Rows.Count);//7938 

vedrete 7938 (ultimo numero di riga sul tuo screenshot). E quando inserisci una nuova riga, questa viene inserita nella posizione 7939. contenuto vuoto a (7929, 7930, ...) le righe vengono ignorate, perché Excel sa che l'ultimo numero è 7938.

Solutions:

  1. è necessario eliminare tutte le righe dopo il 7928 nel file excel.
  2. È necessario inserire in una posizione specifica.
+0

Grazie mille, Dmitry. Proverò presto la tua soluzione e ti dirò se ha funzionato –

+0

Non sono sicuro di poter inserire dati in una riga specifica. Hai un codice di esempio che puoi includere nella risposta? –

3

Se si utilizza il provider Microsoft.ACE.OLEDB, tenere presente che non supporta un intervallo denominato. È necessario fornire il nome del foglio [Sheet1$] o il nome del foglio seguito dall'intervallo [Sheet1$A1:P7928]. Se l'intervallo non viene fornito, definirà la tabella come intervallo utilizzato, che potrebbe contenere righe vuote.

Un modo per gestire le righe vuote è eliminarle, ma il driver non supporta l'operazione DELETE.

Un altro modo è quello di contare prima il numero di righe con un vuoto Id non e quindi utilizzare il risultato per definire l'intervallo della tabella per la INSERT dichiarazione:

using (OleDbConnection conn = new OleDbConnection(connectionString)) { 
    conn.Open(); 

    string SheetName = "Sheet1"; 
    string TableRange = "A1:P{0}"; 

    // count the number of non empty rows 
    using (var cmd1 = new OleDbCommand(null, conn)) { 
     cmd1.CommandText = String.Format(
      "SELECT COUNT(*) FROM [{0}$] WHERE ID IS NOT NULL;" 
      , SheetName); 

     TableRange = string.Format(TableRange, (int)cmd1.ExecuteScalar() + 1); 
    } 

    // insert a new record 
    using (var cmd2 = new OleDbCommand(null, conn)) { 
     cmd2.CommandText = String.Format(
      "INSERT INTO [{0}${1}] (ID, Title, NTV_DB, Type) VALUES(7959, 8,'e','Type1');" 
      , SheetName, TableRange); 

     cmd2.ExecuteNonQuery(); 
    } 
} 
+0

Suggerite di occuparsi delle righe vuote? non è davvero un problema. Il vero problema è come inserire le righe all'interno dell'oggetto Table –

-1

Prova questa

private void GetExcelSheets(string FilePath, string Extension, string isHDR) 
{ 
string conStr=""; 
switch (Extension) 
{ 
    case ".xls": //Excel 97-03 
     conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"] 
       .ConnectionString; 
     break; 
    case ".xlsx": //Excel 07 
     conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"] 
       .ConnectionString; 
     break; 
} 

//Get the Sheets in Excel WorkBoo 
conStr = String.Format(conStr, FilePath, isHDR); 
OleDbConnection connExcel = new OleDbConnection(conStr); 
OleDbCommand cmdExcel = new OleDbCommand(); 
OleDbDataAdapter oda = new OleDbDataAdapter(); 
cmdExcel.Connection = connExcel; 
connExcel.Open(); 

//Bind the Sheets to DropDownList 
ddlSheets.Items.Clear(); 
ddlSheets.Items.Add(new ListItem("--Select Sheet--", ""));  
ddlSheets.DataSource=connExcel 
     .GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 
ddlSheets.DataTextField = "TABLE_NAME"; 
ddlSheets.DataValueField = "TABLE_NAME"; 
ddlSheets.DataBind(); 
connExcel.Close(); 
txtTable.Text = ""; 
lblFileName.Text = Path.GetFileName(FilePath); 
Panel2.Visible = true; 
Panel1.Visible = false; 
} 
+0

Adit, non sono sicuro del motivo per cui si desidera associare i fogli a DropDownList ... –

Problemi correlati