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.

74 lines
2.0 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Apewer.Internals
  5. {
  6. internal class CsvHelper
  7. {
  8. /// <summary>读取 .CSV 文件。</summary>
  9. public static List<List<string>> ReadCSV(string argText)
  10. {
  11. var result = new List<List<string>>();
  12. if (string.IsNullOrEmpty(argText)) return result;
  13. var rows = argText.Split('\n');
  14. var vramarray = new List<string[]>();
  15. foreach (var row in rows)
  16. {
  17. var list = ResolveCSV(row);
  18. if (list.Count > 0) result.Add(list);
  19. }
  20. return result;
  21. }
  22. /// <summary>解析 .CSV 文件。</summary>
  23. private static List<string> ResolveCSV(string argRowText)
  24. {
  25. if (string.IsNullOrEmpty(argRowText)) return new List<string>();
  26. var trim = argRowText.Trim();
  27. if (string.IsNullOrEmpty(trim)) return new List<string>();
  28. var list = new List<string>();
  29. var quote = false;
  30. var cell = "";
  31. for (int i = 0; i < argRowText.Length; i++)
  32. {
  33. var vchar = argRowText[i];
  34. switch (vchar)
  35. {
  36. case '"':
  37. if (!quote) cell = "";
  38. quote = !quote;
  39. break;
  40. case ',':
  41. if (quote)
  42. {
  43. cell += vchar;
  44. }
  45. else
  46. {
  47. list.Add(cell.Trim());
  48. cell = "";
  49. }
  50. break;
  51. default:
  52. cell += vchar;
  53. break;
  54. }
  55. }
  56. if (!string.IsNullOrEmpty(cell))
  57. {
  58. list.Add(cell.Trim());
  59. cell = "";
  60. }
  61. return list;
  62. }
  63. }
  64. }