ExcelRelatorioWriter.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using AGEHAB.RelatorioSeadIpasgo.Application.Abstractions;
  2. using ClosedXML.Excel;
  3. namespace AGEHAB.RelatorioSeadIpasgo.Infrastructure.Excel;
  4. public class ExcelRelatorioWriter : IExcelRelatorioWriter
  5. {
  6. public void Escrever(string tituloRelatorio, IReadOnlyList<dynamic> linhas, string caminhoArquivo, CancellationToken cancellationToken)
  7. {
  8. cancellationToken.ThrowIfCancellationRequested();
  9. using var workbook = new XLWorkbook();
  10. var worksheet = workbook.Worksheets.Add(tituloRelatorio);
  11. var primeiraLinha = linhas.FirstOrDefault();
  12. if (primeiraLinha != null)
  13. {
  14. var dict = (IDictionary<string, object>)primeiraLinha;
  15. var colunas = dict.Keys.ToList();
  16. for (int i = 0; i < colunas.Count; i++)
  17. {
  18. worksheet.Cell(1, i + 1).Value = colunas[i];
  19. worksheet.Cell(1, i + 1).Style.Font.Bold = true;
  20. worksheet.Cell(1, i + 1).Style.Fill.BackgroundColor = XLColor.LightGray;
  21. }
  22. int row = 2;
  23. foreach (var linha in linhas)
  24. {
  25. cancellationToken.ThrowIfCancellationRequested();
  26. var linhaDict = (IDictionary<string, object>)linha;
  27. for (int i = 0; i < colunas.Count; i++)
  28. {
  29. var valor = linhaDict[colunas[i]];
  30. if (valor is decimal decimalValue)
  31. {
  32. worksheet.Cell(row, i + 1).Value = decimalValue;
  33. worksheet.Cell(row, i + 1).Style.NumberFormat.Format = "#,##0.00";
  34. }
  35. else if (valor is int intValue)
  36. {
  37. worksheet.Cell(row, i + 1).Value = intValue;
  38. }
  39. else
  40. {
  41. worksheet.Cell(row, i + 1).Value = valor?.ToString() ?? "";
  42. }
  43. }
  44. row++;
  45. }
  46. }
  47. worksheet.Columns().AdjustToContents();
  48. workbook.SaveAs(caminhoArquivo);
  49. }
  50. }