csv_output.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #pragma once
  2. #include <util/string/printf.h>
  3. #include <util/stream/str.h>
  4. #include <util/generic/set.h>
  5. #include "data.h"
  6. namespace NAnalytics {
  7. inline TString ToCsv(const TTable& in, TString sep = TString("\t"), bool head = true)
  8. {
  9. TSet<TString> cols;
  10. bool hasName = false;
  11. for (const TRow& row : in) {
  12. hasName = hasName || !row.Name.empty();
  13. for (const auto& kv : row) {
  14. cols.insert(kv.first);
  15. }
  16. }
  17. TStringStream ss;
  18. if (head) {
  19. bool first = true;
  20. if (hasName) {
  21. ss << (first? TString(): sep) << "Name";
  22. first = false;
  23. }
  24. for (const TString& c : cols) {
  25. ss << (first? TString(): sep) << c;
  26. first = false;
  27. }
  28. ss << Endl;
  29. }
  30. for (const TRow& row : in) {
  31. bool first = true;
  32. if (hasName) {
  33. ss << (first? TString(): sep) << row.Name;
  34. first = false;
  35. }
  36. for (const TString& c : cols) {
  37. ss << (first? TString(): sep);
  38. first = false;
  39. TString value;
  40. ss << (row.GetAsString(c, value) ? value : TString("-"));
  41. }
  42. ss << Endl;
  43. }
  44. return ss.Str();
  45. }
  46. }