¿Cómo escribir Excel abriéndolo programáticamente con Microsoft.Office.Interop.Excel dll?

StackOverflow https://stackoverflow.com/questions/1648125

  •  22-07-2019
  •  | 
  •  

Pregunta

Quiero usar Microsoft.Office.Interop.Excel dll para escribir los datos en la hoja de Excel. Tengo un código:

if (System.IO.File.Exists(strFileName))
{
    System.IO.File.SetAttributes(strFileName, FileAttributes.Normal);
    System.IO.File.Delete(strFileName);
}

// Open an instance of excel. Create a new workbook.
// A workbook by default has three sheets, so if you just want 
//a single one, delete sheet 2 and 3

Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Excel._Workbook xlWB = (Excel._Workbook)xlApp.Workbooks.Add(Missing.Value);

Excel._Worksheet xlSheet = (Excel._Worksheet)xlWB.Sheets[1];
((Excel._Worksheet)xlWB.Sheets[2]).Delete();
((Excel._Worksheet)xlWB.Sheets[2]).Delete();

xlSheet.Name = strSheetName;

// Write a value into A1
xlSheet.Cells[2, 1] = "Tags";
xlSheet.Cells[2, 2] = "Leak Test";
xlSheet.Cells[2, 3] = "FIR";
xlSheet.Cells[2, 4] = "SOP";

xlWB.SaveAs(strFileName, Missing.Value, Missing.Value, Missing.Value, 
Missing.Value,Missing.Value, 
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, 
Missing.Value, Missing.Value, Missing.Value, Missing.Value);
xlApp.Quit();

// Release the COM object, set the Excel variables to Null, and tell the 
//Garbage Collector to do its thing
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWB);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);

xlSheet = null;
xlWB = null;
xlApp = null;

Ahora quiero abrir el archivo de Excel existente desde la ruta & amp; luego ponga algunos datos en la hoja de Excel que nombramos proporcionó & amp; entonces se guardará en una ruta específica desde la programación.

Responda la fuente si hay alguna que pueda abrir el archivo de Excel existente & amp; que se puede agregar & amp; guardar con otro nombre.

Saludos, Girish

¿Fue útil?

Solución

Consulte aquí para obtener información .

Otros consejos

ExcelPackage ya no se mantiene. Parece tener algunos errores. Leyendo comentarios allí, he encontrado http://epplus.codeplex.com/

Se basa en ExcelPackage y hereda sus licencias (GPL), por lo que puede no satisfacer sus requisitos.

Si está utilizando la versión 2007 de Excel, recomendaría usar ExcelPackage en su lugar, es una implementación del estándar OpenXML, es mucho más rápido y mucho menos complicado que la interoperabilidad COM, y puede ejecutarlo en una máquina que ni siquiera tiene instalado Excel (Office), como en su servidor web.

Muy recomendable, pero limitado a Excel 2007 y versiones posteriores.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top