Ejemplo n.º 1
0
        public ExcelWorksheet WriteToWorksheet(IEnumerable <T> items, ExcelWorksheet worksheet, bool autoFit = true, Action <ExcelRange> headerRowConfig = null, int startRow = 1)
        {
            var currentRow = startRow;

            var sortedHeaders = PropertyMappings.OrderByDescending(i => i.Order).Select(i => i.Header)
                                .Distinct()
                                .Select((excel, index) => new { Index = index, Value = excel })
                                .ToDictionary(i => i.Index + 1, i => i.Value);

            var mapHeaders = sortedHeaders.ToDictionary(i => i.Value, i => i.Key);

            foreach (var(key, value) in sortedHeaders)
            {
                var worksheetCell = worksheet.Cells[currentRow, key];
                worksheetCell.Value = value;
                headerRowConfig?.Invoke(worksheetCell);
            }

            currentRow++;

            foreach (var item in items)
            {
                foreach (var propertyMapping in PropertyMappings)
                {
                    var value = propertyMapping.GetValue(item);
                    worksheet.Cells[currentRow, mapHeaders[propertyMapping.Header]].Value = value;

                    if (!string.IsNullOrEmpty(propertyMapping.Format))
                    {
                        worksheet.Cells[currentRow, mapHeaders[propertyMapping.Header]].Style.Numberformat.Format =
                            propertyMapping.Format;
                    }
                }

                currentRow++;
            }

            if (autoFit)
            {
                worksheet.AutoFit();
            }

            return(worksheet);
        }