CoreComponentExporter es una biblioteca de código abierto que proporciona métodos optimizados y fáciles de usar para exportar datos de DataTable e IEnumerable a archivos Excel (.xlsx, .xlsm, .xlsb, .xltx, .xltm). Utiliza NPOI para la generación eficiente de archivos Excel y SixLabors.ImageSharp para el manejo de imágenes. Compatible con múltiples versiones de .NET (6.0, 7.0, 8.0 y 9.0), lo que la convierte en una herramienta ideal para desarrolladores que buscan una solución de exportación de datos flexible y escalable.
$ dotnet add package CoreComponentExporterA powerful and flexible library for exporting data to various file formats with support for generics, advanced formatting, and robust error handling. Part of the DeveloperKit ecosystem, this component provides seamless integration with .NET applications for all your data export needs.
Multiple Export Formats
Advanced Excel Capabilities
Developer Experience
Install the package via NuGet Package Manager Console:
dotnet add package DevKit.Exporter
<div align="center">
Made with ❤️ by the DeveloperKit Team
</div>
- Limpiar recursos correctamente
- Usar rutas seguras
Or add the package reference to your .csproj file:
<PackageReference Include="DevKit.Exporter" Version="1.0.0" />
public void ConfigureServices(IServiceCollection services)
{
// Add Exporter with default settings
services.AddExporter();
// Register other services
services.AddControllers();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddExporter(options =>
{
// Configure default export settings
options.DefaultExcelSettings = new ExcelExportSettings
{
AutoFitColumns = true,
IncludeHeader = true,
SheetName = "Export",
HeaderStyle = new CellStyle
{
FontBold = true,
BackgroundColor = Color.LightGray,
HorizontalAlignment = HorizontalAlignment.Center
},
DataStyle = new CellStyle
{
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Center
}
};
// Configure CSV settings
options.DefaultCsvSettings = new CsvExportSettings
{
Delimiter = ",",
IncludeHeader = true,
Encoding = Encoding.UTF8
};
// Enable detailed logging
options.EnableLogging = true;
// Configure default date/time formats
options.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
options.DateFormat = "yyyy-MM-dd";
options.TimeFormat = "HH:mm:ss";
});
// Register other services
services.AddControllers();
}
{
"ExporterOptions": {
"DefaultExcelSettings": {
"AutoFitColumns": true,
"IncludeHeader": true,
"SheetName": "Export",
"HeaderStyle": {
"FontBold": true,
"BackgroundColor": "LightGray",
"HorizontalAlignment": "Center"
},
"DataStyle": {
"HorizontalAlignment": "Left",
"VerticalAlignment": "Center"
}
},
"DefaultCsvSettings": {
"Delimiter": ",",
"IncludeHeader": true,
"Encoding": "UTF8"
},
"EnableLogging": true,
"DateTimeFormat": "yyyy-MM-dd HH:mm:ss",
"DateFormat": "yyyy-MM-dd",
"TimeFormat": "HH:mm:ss"
}
}
public class ReportService
{
private readonly IExcelExporter _excelExporter;
private readonly ILogger<ReportService> _logger;
public ReportService(IExcelExporter excelExporter, ILogger<ReportService> logger)
{
_excelExporter = excelExporter;
_logger = logger;
}
public async Task<byte[]> ExportToExcelAsync<T>(IEnumerable<T> data, string sheetName = "Export")
{
try
{
var options = new ExcelExportOptions<T>
{
SheetName = sheetName,
AutoFitColumns = true,
IncludeHeader = true,
HeaderStyle = new CellStyle
{
FontBold = true,
BackgroundColor = Color.LightBlue,
HorizontalAlignment = HorizontalAlignment.Center
},
DataStyle = new CellStyle
{
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Center
}
};
return await _excelExporter.ExportToByteArrayAsync(data, options);
}
catch (ExportException ex)
{
_logger.LogError(ex, "Error exporting data to Excel");
throw;
}
}
}
public async Task<byte[]> ExportMultipleSheetsAsync(
IEnumerable<Customer> customers,
IEnumerable<Order> orders)
{
var workbook = new ExcelWorkbook();
// Add first sheet
var customerSheet = workbook.AddWorksheet("Customers");
await customerSheet.WriteDataAsync(customers, new ExcelExportOptions<Customer>
{
AutoFitColumns = true
});
// Add second sheet
var ordersSheet = workbook.AddWorksheet("Orders");
await ordersSheet.WriteDataAsync(orders, new ExcelExportOptions<Order>
{
AutoFitColumns = true,
IncludeHeader = true,
HeaderStyle = new CellStyle { FontBold = true }
});
// Export to byte array
using var stream = new MemoryStream();
await workbook.SaveAsAsync(stream);
return stream.ToArray();
}
public async Task<byte[]> ExportWithCustomMapping(IEnumerable<Product> products)
{
var options = new ExcelExportOptions<Product>
{
SheetName = "Products",
AutoFitColumns = true,
IncludeHeader = true,
ColumnMappings = new List<ColumnMapping<Product>>
{
new()
{
Property = p => p.Id,
Header = "ID",
Width = 10,
Style = new CellStyle { HorizontalAlignment = HorizontalAlignment.Center }
},
new()
{
Property = p => p.Name,
Header = "Product Name",
Width = 30,
Style = new CellStyle { FontBold = true }
},
new()
{
Property = p => p.Price,
Header = "Price (USD)",
Format = "$#,##0.00",
Style = new CellStyle
{
NumberFormat = NumberFormat.Currency,
HorizontalAlignment = HorizontalAlignment.Right
}
},
new()
{
Property = p => p.StockQuantity,
Header = "In Stock",
Style = new CellStyle { HorizontalAlignment = HorizontalAlignment.Center },
ConditionalFormats = new List<ConditionalFormat>
{
new()
{
Condition = cell => (int)cell.Value < 10,
Style = new CellStyle { BackgroundColor = Color.LightPink }
},
new()
{
Condition = cell => (int)cell.Value == 0,
Style = new CellStyle
{
BackgroundColor = Color.Red,
FontColor = Color.White
}
}
}
},
new()
{
Property = p => p.LastRestocked,
Header = "Last Restocked",
Format = "yyyy-MM-dd",
Style = new CellStyle { HorizontalAlignment = HorizontalAlignment.Center }
}
}
};
return await _excelExporter.ExportToByteArrayAsync(products, options);
}
public async Task<string> ExportToCsvAsync<T>(IEnumerable<T> data, string delimiter = ",")
{
var options = new CsvExportOptions
{
Delimiter = delimiter,
IncludeHeader = true,
Encoding = Encoding.UTF8
};
return await _csvExporter.ExportToStringAsync(data, options);
}
IExcelExporterMain interface for Excel export operations.
Methods:
Task<byte[]> ExportToByteArrayAsync<T>(IEnumerable<T> data, ExcelExportOptions<T> options = null)Task<Stream> ExportToStreamAsync<T>(IEnumerable<T> data, ExcelExportOptions<T> options = null)Task ExportToFileAsync<T>(string filePath, IEnumerable<T> data, ExcelExportOptions<T> options = null)Task<ExcelWorkbook> CreateWorkbookAsync<T>(IEnumerable<T> data, ExcelExportOptions<T> options = null)ICsvExporterInterface for CSV export operations.
Methods:
Task<string> ExportToStringAsync<T>(IEnumerable<T> data, CsvExportOptions options = null)Task<byte[]> ExportToByteArrayAsync<T>(IEnumerable<T> data, CsvExportOptions options = null)Task ExportToFileAsync<T>(string filePath, IEnumerable<T> data, CsvExportOptions options = null)ExcelExportOptions<T>Options for exporting data to Excel.
Properties:
string SheetName - Name of the worksheet (default: "Sheet1")bool AutoFitColumns - Whether to auto-fit column widths (default: true)bool IncludeHeader - Whether to include column headers (default: true)CellStyle HeaderStyle - Style for header cellsCellStyle DataStyle - Default style for data cellsIList<ColumnMapping<T>> ColumnMappings - Custom column mappingsIDictionary<string, string> CustomProperties - Custom document propertiesbool FreezeHeader - Whether to freeze the header row (default: true)bool ShowGridLines - Whether to show grid lines (default: true)CsvExportOptionsOptions for exporting data to CSV.
Properties:
string Delimiter - Field delimiter (default: ",")bool IncludeHeader - Whether to include column headers (default: true)Encoding Encoding - Text encoding (default: UTF-8)string NewLine - Line terminator (default: Environment.NewLine)bool QuoteAllFields - Whether to quote all fields (default: false)Input Validation
Data Protection
Performance
Batch Processing
Memory Management
IAsyncDisposable for async operationsArrayPool<T> for large arraysCaching
This project is licensed under the MIT License - see the LICENSE file for details.
Contributions are welcome! Please read our contributing guidelines for details on our code of conduct and the process for submitting pull requests.
For support, please open an issue in our issue tracker.
await data.ExportToCsvAsync("archivo.csv");
var filteredData = data.Where(x => x.IsActive)
.ExportToCsv("archivo_filtrado.csv");
var transformedData = data.Select(x => new {
x.Id,
x.Name,
FormattedDate = x.CreatedDate.ToString("dd/MM/yyyy")
});
transformedData.ExportToCsv("archivo_transformado.csv");
Para reportar errores o solicitar características, por favor abre un issue en el repositorio de GitHub.
Este proyecto está bajo licencia MIT. Consulta el archivo LICENSE para más detalles.