You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.5KB

  1. using ClosedXML.Excel;
  2. using System.Text;
  3. namespace ToolsServices
  4. {
  5. public static class XlsxService
  6. {
  7. #region Méthodes publiques
  8. public static string ExtractXlsxFromBytes(byte[] bytes)
  9. {
  10. using var ms = new MemoryStream(bytes);
  11. using var workbook = new XLWorkbook(ms);
  12. var builder = new StringBuilder();
  13. foreach (var ws in workbook.Worksheets)
  14. {
  15. builder.AppendLine($"--- Feuille : {ws.Name} ---");
  16. var range = ws.RangeUsed();
  17. if (range == null)
  18. continue;
  19. foreach (var row in range.Rows())
  20. {
  21. foreach (var cell in row.Cells())
  22. {
  23. var value = cell.GetFormattedString();
  24. if (!string.IsNullOrWhiteSpace(value))
  25. {
  26. builder.Append(value).Append(" ");
  27. }
  28. }
  29. builder.AppendLine();
  30. }
  31. builder.AppendLine();
  32. }
  33. return builder.ToString();
  34. }
  35. public static string ExtractTextFromXlsx(string fileFullname)
  36. {
  37. LoggerService.LogInfo($"XlsxService.ExtractTextFromXlsx : {fileFullname}");
  38. using var workbook = new XLWorkbook(fileFullname);
  39. return string.Join("\n", workbook.Worksheets.SelectMany(ws => ws.CellsUsed().Select(c => c.GetValue<string>())));
  40. }
  41. public static string ExtractTextFromCsv(string fileFullname)
  42. {
  43. LoggerService.LogInfo($"XlsxService.ExtractTextFromCsv : {fileFullname}");
  44. // Lire la première ligne du fichier
  45. var lignes = File.ReadAllLines(fileFullname);
  46. if (lignes.Length == 0) return string.Empty;
  47. var premiereLigne = lignes[0];
  48. // Compter les séparateurs
  49. int countPointVirgule = premiereLigne.Count(c => c == ';');
  50. int countVirgule = premiereLigne.Count(c => c == ',');
  51. // Choisir le séparateur le plus utilisé
  52. char separateur = countPointVirgule >= countVirgule ? ';' : ',';
  53. // Parser le fichier
  54. var lignesFormatees = lignes
  55. .Select(ligne => ligne.Split(separateur))
  56. .Select(colonnes => string.Join(" | ", colonnes));
  57. return string.Join(Environment.NewLine, lignesFormatees);
  58. }
  59. #endregion
  60. }
  61. }