2009-01-23 29 views
20

Estoy tratando de abrir un archivo de Excel y llenar sus celdas con datos? He hecho la siguiente codificación hasta el momento.C#: ¿Cómo acceder a una celda de Excel?

Actualmente estoy en esta etapa con el siguiente código, pero todavía estoy recibiendo errores:

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

Estos son los 2 principales errores que estoy recibiendo:

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 

Respuesta

20

Si está intentando para automatizar Excel, probablemente no debería abrir un documento de Word y usar la automatización de Word;)

Mira esto, debería g y se inició,

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

Y aquí es un poco de código. Está extraído de algunos de mis códigos y tiene muchas cosas eliminadas, por lo que no hace nada y puede que no compile o funcione exactamente, pero debería hacerlo funcionar. Está orientado a la lectura, pero debe apuntarle en la dirección correcta.

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

También se puede hacer

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

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

Y si es necesario insertar filas/columnas

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

código incorrecto siento publicado, he corregido – tksy

3

Creo, que usted tiene que declarar la hoja asociado!

Pruebe algo como esto

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

dónde encontraste esto? Y dos puntos es una mala práctica ... – nawfal

1

Cómo trabajo para automatizar Oficina/Excel:

  1. grabar una macro, esto generará una plantilla de VBA
  2. Editar la plantilla de VBA por lo que se coincide con mis necesidades
  3. Convierte a VB.Net (Un paso pequeño para hombres)
  4. Déjalo en VB.Net, mucho más fácil como hacerlo con C#
+1

de la pregunta, él lo quiere en C#, pero sí que estaría bien para VB.Net. –

1

Probar:

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

esto no es correcto, OP pregunta cómo abrir un libro de trabajo, no cómo crear uno nuevo ... (está utilizando el método .add). –

1

simple.

Para abrir un libro de trabajo. Uso xlapp.workbooks.Open()

en la que han declarado previamente y xlApp instanitated como así .. Excel.Application xlApp = new Excel.Applicaton();

parámetros son correctos.

siguiente Asegúrese de que utiliza la propiedad Value2 cuando se asigna un valor a la celda utilizando la propiedad células o el objeto gama.

1

Esto funciona muy bien para mí

 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

Puede utilizar el código de abajo; que está funcionando bien para mí:

newWorkbook = appExcel.Workbooks.Add(); 
Cuestiones relacionadas