ExcelWriter.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. public void Write<T>(IEnumerable<T> values, string? worksheetName = null, bool append = false) where T : class, new()
  25. {
  26. var xlWorksheet = xlWorkbook.Worksheets.FirstOrDefault(x => x.Name.Equals(worksheetName, StringComparison.InvariantCultureIgnoreCase));
  27. xlWorksheet ??= !string.IsNullOrWhiteSpace(worksheetName) ?
  28. xlWorkbook.AddWorksheet(worksheetName)
  29. : xlWorkbook.Worksheets.Count == 0 ? xlWorkbook.AddWorksheet() : xlWorkbook.Worksheets.First();
  30. Write(values, xlWorksheet, append);
  31. }
  32. private static void Write<T>(IEnumerable<T> values, IXLWorksheet worksheet, bool append) where T : class, new()
  33. {
  34. var enumerable = values as T[] ?? values.ToArray();
  35. if (!enumerable.Any()) return;
  36. var rowIndex = append switch
  37. {
  38. true => worksheet.LastRowUsed().RowNumber() + 1,
  39. false => GenerateHeader<T>(worksheet),
  40. };
  41. foreach (var value in enumerable)
  42. {
  43. var cellIndex = 1;
  44. var properties = typeof(T).GetProperties();
  45. foreach (var property in properties)
  46. {
  47. worksheet.Cell(rowIndex, cellIndex).Value = property.GetValue(value) as string;
  48. cellIndex++;
  49. }
  50. rowIndex++;
  51. }
  52. }
  53. public void SaveAs(string path, IExcelConverter? converter = null)
  54. {
  55. xlWorkbook.SaveAs(path);
  56. converter?.MakeCompatible(path);
  57. }
  58. }