2009-01-23 15 views
20

Sto tentando di aprire un file Excel e popolare le sue celle con i dati? Ho fatto la seguente codifica finora.C#: come accedere a una cella di Excel?

Attualmente sono in questa fase con il seguente codice, ma ancora sto ottenendo gli errori:

Microsoft.Office.Interop.Excel.ApplicationClass appExcel = 
       new Microsoft.Office.Interop.Excel.ApplicationClass(); 
try 
{ 
    // is there already such a file ? 
    if (System.IO.File.Exists("C:\\csharp\\errorreport1.xls")) 
    { 
     // then go and load this into excel 
     Microsoft.Office.Interop.Excel.Workbooks.Open(
      "C:\\csharp\\errorreport1.xls", true, false, 
      Missing.Value, Missing.Value, Missing.Value, Missing.Value, 
      Missing.Value, Missing.Value, Missing.Value, Missing.Value, 
      Missing.Value, Missing.Value, Missing.Value, Missing.Value); 
    } 
    else 
    { 
     // if not go and create a workbook: 
     newWorkbook = appExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet); 
     Microsoft.Office.Interop.Excel._Worksheet excelWorksheet = 
      (Microsoft.Office.Interop.Excel._Worksheet) 
       newWorkBook.Worksheets.get_Item(1); 
    } 
i++; 
j = 1; 

j++; 
objsheet.Cells(i, j).Value = "Tabelle: " + rs.Fields["Table_Name"]; 
j++; 
objsheet.Cells(i, j).Value = "kombinationsschluessel:FALL " 
           + rs3.Fields[1].Value; 
j++; 
objsheet.Cells(i, j).Value = "Null Value: "; 
j++; 
objsheet.Cells(i, j).Value = "Updated with 888"; 

Questi sono i primi 2 errori che sto ottenendo:

Error 1 An object reference is required for the nonstatic field, method, or 
     property 'Microsoft.Office.Interop.Excel.Workbooks.Open(string, object, 
     object, object, object, object, object, object, object, object, object, 
     object, object, object, object)' 

Error 2 The name 'newWorkbook' does not exist in the current context 

risposta

20

Se si sta cercando per automatizzare Excel, probabilmente non dovresti aprire un documento Word e utilizzare l'automazione di Word;)

Controllare questo, dovrebbe essere et hai iniziato,

http://www.codeproject.com/KB/office/package.aspx

Ed ecco qualche codice. È preso da parte del mio codice e ha un sacco di cose cancellate, quindi non fa nulla e potrebbe non essere compilato o funzionare esattamente, ma dovrebbe farti andare avanti. È orientato alla lettura, ma dovrebbe indirizzarti nella giusta direzione.

Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet; 

if (sheet != null) 
{ 
    Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange; 
    if (range != null) 
    { 
     int nRows = usedRange.Rows.Count; 
     int nCols = usedRange.Columns.Count; 
     foreach (Microsoft.Office.Interop.Excel.Range row in usedRange.Rows) 
     { 
      string value = row.Cells[0].FormattedValue as string; 
     } 
    } 
} 

Si può anche fare

Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets; 

if (sheets != null) 
{ 
    foreach (Microsoft.Office.Interop.Excel.Worksheet sheet in sheets) 
    { 
      // Do Stuff 
    } 
} 

E se avete bisogno di inserire righe/colonne

// Inserts a new row at the beginning of the sheet 
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range("A1", Type.Missing); 
a1.EntireRow.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing); 
+0

scusa codice errato pubblicato, lo ho corretto – tksy

3

penso, che si deve dichiarare il foglio associato!

provare qualcosa di simile

objsheet(1).Cells[i,j].Value; 
+0

dove l'hai trovato? E due punti è una cattiva pratica .. – nawfal

1

Come io lavoro per automatizzare Office/Excel:

  1. registrare una macro, questo genererà un modello VBA
  2. Modificare il modello VBA in modo da esso corrisponde alle mie esigenze
  3. Converti in VB.Net (Un piccolo passo per gli uomini)
  4. Lascia in VB.Net, molto di più facile come farlo utilizzando C#
+1

dalla domanda, lo vuole in C#, ma sì, che andrebbe bene per VB.Net. –

1

Prova:

Excel.Application oXL; 
Excel._Workbook oWB; 
Excel._Worksheet oSheet; 
Excel.Range oRng; 

oXL = new Excel.Application(); 
oXL.Visible = true; 
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value)); 

oSheet = (Excel._Worksheet)oWB.Worksheets; 
oSheet.Activate(); 

oSheet.Cells[3, 9] = "Some Text" 
+0

questo non è corretto, OP sta chiedendo come aprire una cartella di lavoro, non come crearne una nuova ... (stai usando il metodo .add). –

1

semplice.

Per aprire una cartella di lavoro. Usa xlapp.workbooks.Open()

cui è stato precedentemente dichiarato e xlApp instanitated come così .. Excel.Application xlApp = new Excel.Applicaton();

I parametri

sono corretti.

Quindi assicurarsi di utilizzare la proprietà Valore2 quando si assegna un valore alla cella utilizzando la proprietà celle o l'oggetto intervallo.

1

Questo funziona bene per me

 Excel.Application oXL = null; 
     Excel._Workbook oWB = null; 
     Excel._Worksheet oSheet = null; 

     try 
     { 
      oXL = new Excel.Application(); 
      string path = @"C:\Templates\NCRepTemplate.xlt"; 
      oWB = oXL.Workbooks.Open(path, 0, false, 5, "", "", 
       false, Excel.XlPlatform.xlWindows, "", true, false, 
       0, true, false, false); 

      oSheet = (Excel._Worksheet)oWB.ActiveSheet; 
      oSheet.Cells[2, 2] = "Text"; 
1

È possibile utilizzare il codice qui sotto; sta funzionando bene per me:

newWorkbook = appExcel.Workbooks.Add();