Biblioteca .NET de código abierto para manipular hojas de cálculo de Excel

ClosedXML le permite leer, manipular y escribir documentos de Microsoft Excel

ClosedXML es una API C# de código abierto para leer, manipular y escribir documentos de Microsoft Excel 2007+ (.xlsx, .xlsm). La API le permite crear archivos de Excel sin usar la aplicación de Excel y leer archivos usando las características mejoradas.

Con la API, puede diseñar sus libros de trabajo mediante el uso de colores de fondo y bordes de celdas. Puede agregar, eliminar y mover sus hojas de trabajo y administrar tipos de datos dentro de Excel.

Previous Next

Primeros pasos con ClosedXML

La forma recomendada de instalar ClosedXML es desde NuGet. Utilice el siguiente comando para una instalación más rápida.

Instalar ClosedXML desde NuGet

 Install-Package ClosedXML

Cree nuevos libros de trabajo gratis usando C#

CLosedXML permite a los desarrolladores C.NET crear nuevas hojas de trabajo excelentes. Puedes crear un libro de cocina en blanco utilizando el método XLWorkbook(). La biblioteca ha incluido varias características importantes para la gestión de sus documentos de hoja de trabajo. Permite añadir hojas de trabajo en su libro de cocina, añadir células y columnas, aplicar estilos a filas y columnas, eliminar las células no deseadas y muchos más.

Crear Nuevos libros de cocina a través de .NET API


using (var workbook = new XLWorkbook())
{
    var worksheet = workbook.Worksheets.Add("Sample Sheet");
    worksheet.Cell("A1").Value = "Hello World!";
    worksheet.Cell("A2").FormulaA1 = "=MID(A1, 7, 5)";
    workbook.SaveAs("HelloWorld.xlsx");
}

Estilo de hojas de Excel usando C#

La fuente abierta ClosedXML API permite a los desarrolladores de software aplicar estilos a sus hojas de excelencia con sólo un par de líneas de código C. El API está enriquecido con características de estilo incluyendo alineación, frontera, relleno, fuente, formato de número, filas de estilo, columnas, y más. La biblioteca también permite a los usuarios modificar el estilo según sus necesidades.

Cómo aplicar Estilos a Excel Sheets a través de la Biblioteca C


            var path = Program.BaseCreatedDirectory;
            new StyleFont().Create(Path.Combine(path, "styleFont.xlsx"));
            new StyleFill().Create(Path.Combine(path, "styleFill.xlsx"));
            new StyleBorder().Create(Path.Combine(path, "styleBorder.xlsx"));
            new StyleAlignment().Create(Path.Combine(path, "styleAlignment.xlsx"));
            new StyleNumberFormat().Create(Path.Combine(path, "styleNumberFormat.xlsx"));
            new StyleIncludeQuotePrefix().Create(Path.Combine(path, "styleIncludeQuotePrefix.xlsx"));

Uso de filtros automáticos en Excel usando C#

La biblioteca ClosedXML ha incluido soporte completo para aplicar filtros dentro de sus hojas de trabajo excelentes. La biblioteca ha incluido varios tipos de filtros para la comodidad del usuario. Puede aplicar el filtro a un rango específico, aplicar un filtro a valores y crear sus propios filtros personalizados también.

Cómo aplicar filtros automáticos en Excel vía C

public class DynamicAutoFilter : IXLExample
    {
        public void Create(string filePath)
        {
            var wb = new XLWorkbook();
            IXLWorksheet ws;
            #region Single Column Numbers
            String singleColumnNumbers = "Single Column Numbers";
            ws = wb.Worksheets.Add(singleColumnNumbers);
            // Add a bunch of numbers to filter
            ws.Cell("A1").SetValue("Numbers")
                         .CellBelow().SetValue(2)
                         .CellBelow().SetValue(3)
                         .CellBelow().SetValue(3)
                         .CellBelow().SetValue(5)
                         .CellBelow().SetValue(1)
                         .CellBelow().SetValue(4);
            // Add filters
            ws.RangeUsed().SetAutoFilter().Column(1).AboveAverage();
            // Sort the filtered list
            //ws.AutoFilter.Sort(1);
            #endregion
            #region Multi Column
            String multiColumn = "Multi Column";
            ws = wb.Worksheets.Add(multiColumn);
            ws.Cell("A1").SetValue("First")
             .CellBelow().SetValue("B")
             .CellBelow().SetValue("C")
             .CellBelow().SetValue("C")
             .CellBelow().SetValue("E")
             .CellBelow().SetValue("A")
             .CellBelow().SetValue("D");
            ws.Cell("B1").SetValue("Numbers")
                         .CellBelow().SetValue(2)
                         .CellBelow().SetValue(3)
                         .CellBelow().SetValue(3)
                         .CellBelow().SetValue(5)
                         .CellBelow().SetValue(1)
                         .CellBelow().SetValue(4);
            ws.Cell("C1").SetValue("Strings")
             .CellBelow().SetValue("B")
             .CellBelow().SetValue("C")
             .CellBelow().SetValue("C")
             .CellBelow().SetValue("E")
             .CellBelow().SetValue("A")
             .CellBelow().SetValue("D");
            // Add filters
            ws.RangeUsed().SetAutoFilter().Column(2).BelowAverage();
            // Sort the filtered list
            //ws.AutoFilter.Sort(3);
            #endregion
            using (var ms = new MemoryStream())
            {
                wb.SaveAs(ms);
                var workbook = new XLWorkbook(ms);
                #region Single Column Numbers
                //workbook.Worksheet(singleColumnNumbers).AutoFilter.Sort(1, XLSortOrder.Descending);
                #endregion
                #region Multi Column 
                //workbook.Worksheet(multiColumn).AutoFilter.Sort(3, XLSortOrder.Descending);
                #endregion
                workbook.SaveAs(filePath);
                ms.Close();
            }
        }
    }
 Español