ExcelWriter.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using ClosedXML.Excel;
  2. using ExcelORM.Attributes;
  3. namespace ExcelORM;
  4. public class ExcelWriter
  5. {
  6. private readonly IXLWorkbook xlWorkbook;
  7. public ExcelWriter(string? path = null)
  8. {
  9. xlWorkbook = File.Exists(path) ? new XLWorkbook(path) : new XLWorkbook();
  10. }
  11. private static int GenerateHeader<T>(IXLWorksheet worksheet) where T : class, new()
  12. {
  13. var rowIndex = 1;
  14. var cellIndex = 1;
  15. var properties = typeof(T).GetProperties();
  16. foreach (var property in properties)
  17. {
  18. var columnAttribute = property.GetCustomAttributes(typeof(ColumnAttribute), false).FirstOrDefault() as ColumnAttribute;
  19. worksheet.Cell(rowIndex, cellIndex).Value = columnAttribute is { Names.Length: > 0 } ? columnAttribute.Names.First() : property.Name;
  20. cellIndex++;
  21. }
  22. return ++rowIndex;
  23. }
  24. private static void Write<T>(IEnumerable<T> values, IXLWorksheet worksheet, bool append) where T : class, new()
  25. {
  26. var enumerable = values as T[] ?? values.ToArray();
  27. if (!enumerable.Any()) return;
  28. var rowIndex = append switch
  29. {
  30. true => worksheet.LastRowUsed().RowNumber() + 1,
  31. false => GenerateHeader<T>(worksheet),
  32. };
  33. foreach (var value in enumerable)
  34. {
  35. var cellIndex = 1;
  36. var properties = typeof(T).GetProperties();
  37. foreach (var property in properties)
  38. {
  39. var valueToSet = property.GetValue(value);
  40. if (valueToSet == null) continue;
  41. worksheet.Cell(rowIndex, cellIndex).Value = XLCellValue.FromObject(valueToSet);
  42. cellIndex++;
  43. }
  44. rowIndex++;
  45. }
  46. }
  47. public void Write<T>(IEnumerable<T> values, string? worksheetName = null, bool append = false) where T : class, new()
  48. {
  49. var xlWorksheet = xlWorkbook.Worksheets.FirstOrDefault(x => x.Name.Equals(worksheetName, StringComparison.InvariantCultureIgnoreCase));
  50. xlWorksheet ??= !string.IsNullOrWhiteSpace(worksheetName) ?
  51. xlWorkbook.AddWorksheet(worksheetName)
  52. : xlWorkbook.Worksheets.Count == 0 ? xlWorkbook.AddWorksheet() : xlWorkbook.Worksheets.First();
  53. Write(values, xlWorksheet, append);
  54. }
  55. public void SaveAs(string path, IExcelConverter? converter = null)
  56. {
  57. xlWorkbook.SaveAs(path);
  58. converter?.MakeCompatible(path);
  59. }
  60. }