visual studio office microsoft manipular example desde crear con c# excel com office-interop worksheet

c# - studio - microsoft.office.interop.excel download



C#- Cómo agregar una hoja de cálculo de Excel mediante programación-Office XP/2003 (9)

Estoy empezando a jugar con Excel a través de C # para poder automatizar la creación y la adición a un archivo de Excel.

Puedo abrir el archivo y actualizar sus datos y moverme a través de las hojas de trabajo existentes. Mi problema es ¿cómo puedo agregar hojas nuevas?

Lo intenté:

Excel.Worksheet newWorksheet; newWorksheet = (Excel.Worksheet)excelApp.ThisWorkbook.Worksheets.Add( Type.Missing, Type.Missing, Type.Missing, Type.Missing);

Pero obtengo una Excepción COM inferior y mi Google no me ha dado ninguna respuesta.

Excepción de HRESULT: 0x800A03EC La fuente es: "Interop.Excel"

Espero que alguien sea capaz de sacarme de mi miseria.


Otro "Up Tick" para AR ..., pero si no tiene que usar la interoperabilidad lo evitaría por completo. Este producto es bastante interesante: http://www.clearoffice.com/ y proporciona una API muy manejable e intuitiva para la manipulación de archivos Excel y parece ser gratuita. (al menos por el momento) SpreadSheetGear también es excelente pero caro.

Mis dos centavos.


Aquí hay un par de cosas que descubrí:

  1. No puede abrir más de una instancia del mismo objeto al mismo tiempo. Por ejemplo, si instancia un nuevo objeto de hoja de Excel llamado xlsheet1 , debe liberarlo antes de crear otro objeto de hoja de Excel ex xlsheet2 . Parece que COM pierde la pista del objeto y deja un proceso zombie en el servidor.

  2. Usar el método abierto asociado con excel.workbooks también se vuelve difícil de cerrar si tienes varios usuarios accediendo al mismo archivo. Use el método Add en su lugar, funciona igual de bien sin bloquear el archivo. p.ej. xlBook = xlBooks.Add("C:/location/XlTemplate.xls")

  3. Coloque su colección de basura en un bloque o método separado después de liberar los objetos COM.



Esto es lo que solía agregar una hoja de trabajo adicional

Workbook workbook = null; Worksheet worksheet = null; workbook = app.Workbooks.Add(1); workbook.Sheets.Add(); Worksheet additionalWorksheet = workbook.ActiveSheet;


Puede usar OLEDB para crear y manipular archivos de Excel. Vea esta pregunta para enlaces y muestras.


Tuve un problema similar en el nivel de aplicación add-in en VSTO, la excepción HRESULT: 0x800A03EC al agregar una nueva hoja.

El código de error 0x800A03EC (o -2146827284) significa NAME_NOT_FOUND; en otras palabras, ha pedido algo y Excel no puede encontrarlo.

Dominic Zukiewicz @ Excel error HRESULT: 0x800A03EC al intentar obtener rango con el nombre de la celda

Entonces finalmente me di cuenta de que ThisWorkbook desencadenó la excepción. ActiveWorkbook fue correcto.

Excel.Worksheet newSheetException = Globals.ThisAddIn.Application.ThisWorkbook.Worksheets.Add(Type.Missing, sheet, Type.Missing, Type.Missing); Excel.Worksheet newSheetNoException = Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets.Add(Type.Missing, sheet, Type.Missing, Type.Missing);


No olvides incluir Referencia a la Microsoft Excel 12.0/11.0 object Library

using Excel = Microsoft.Office.Interop.Excel; // Include this Namespace

Microsoft.Office.Interop.Excel.Application xlApp = null; Excel.Workbook xlWorkbook = null; Excel.Sheets xlSheets = null; Excel.Worksheet xlNewSheet = null; string worksheetName ="Sheet_Name"; object readOnly1 = false; object isVisible = true; object missing = System.Reflection.Missing.Value; try { xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) return; // Uncomment the line below if you want to see what''s happening in Excel // xlApp.Visible = true; xlWorkbook = xlApp.Workbooks.Open(@"C:/Book1.xls", missing, readOnly1, missing, missing, missing, missing, missing, missing, missing, missing, isVisible, missing, missing, missing); xlSheets = (Excel.Sheets)xlWorkbook.Sheets; // The first argument below inserts the new worksheet as the first one xlNewSheet = (Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing); xlNewSheet.Name = worksheetName; xlWorkbook.Save(); xlWorkbook.Close(Type.Missing, Type.Missing, Type.Missing); xlApp.Quit(); } finally { System.Runtime.InteropServices.Marshal.ReleaseComObject(xlNewSheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheets); System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook); System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp); //xlApp = null; }


Debe agregar una referencia COM en su proyecto a la " Microsoft Excel 11.0 Object Library " , o la versión que sea apropiada.

Este código funciona para mí:

private void AddWorksheetToExcelWorkbook(string fullFilename,string worksheetName) { Microsoft.Office.Interop.Excel.Application xlApp = null; Workbook xlWorkbook = null; Sheets xlSheets = null; Worksheet xlNewSheet = null; try { xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) return; // Uncomment the line below if you want to see what''s happening in Excel // xlApp.Visible = true; xlWorkbook = xlApp.Workbooks.Open(fullFilename, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false); xlSheets = xlWorkbook.Sheets as Sheets; // The first argument below inserts the new worksheet as the first one xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing); xlNewSheet.Name = worksheetName; xlWorkbook.Save(); xlWorkbook.Close(Type.Missing,Type.Missing,Type.Missing); xlApp.Quit(); } finally { Marshal.ReleaseComObject(xlNewSheet); Marshal.ReleaseComObject(xlSheets); Marshal.ReleaseComObject(xlWorkbook); Marshal.ReleaseComObject(xlApp); xlApp = null; } }

Tenga en cuenta que debe tener mucho cuidado al limpiar y liberar correctamente las referencias de objetos COM . Incluido en esa pregunta es una regla general útil: "Nunca use 2 puntos con objetos COM" . En tu código; vas a tener problemas reales con eso. Mi código de demostración anterior NO limpia correctamente la aplicación de Excel, ¡pero es un comienzo!

Algunos otros enlaces que encontré útiles al analizar esta pregunta:

De acuerdo con MSDN

Para usar la interoperabilidad COM, debe tener permisos de seguridad de Administrador o Usuario avanzado.

Espero que ayude.


Quisiera agradecerle por sus excelentes respuestas. @AR., Eres una estrella y funciona perfectamente. Anoche noté que el Excel.exe no se estaba cerrando; así que investigué y descubrí cómo liberar los objetos COM. Aquí está mi código final:

using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.IO; using Excel; namespace testExcelconsoleApp { class Program { private String fileLoc = @"C:/temp/test.xls"; static void Main(string[] args) { Program p = new Program(); p.createExcel(); } private void createExcel() { Excel.Application excelApp = null; Excel.Workbook workbook = null; Excel.Sheets sheets = null; Excel.Worksheet newSheet = null; try { FileInfo file = new FileInfo(fileLoc); if (file.Exists) { excelApp = new Excel.Application(); workbook = excelApp.Workbooks.Open(fileLoc, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false); sheets = workbook.Sheets; //check columns exist foreach (Excel.Worksheet sheet in sheets) { Console.WriteLine(sheet.Name); sheet.Select(Type.Missing); System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet); } newSheet = (Worksheet)sheets.Add(sheets[1], Type.Missing, Type.Missing, Type.Missing); newSheet.Name = "My New Sheet"; newSheet.Cells[1, 1] = "BOO!"; workbook.Save(); workbook.Close(null, null, null); excelApp.Quit(); } } finally { System.Runtime.InteropServices.Marshal.ReleaseComObject(newSheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); newSheet = null; sheets = null; workbook = null; excelApp = null; GC.Collect(); } } } }

Gracias por toda tu ayuda.