CsvUtil.C 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (C) 2008 Emweb bvba, Kessel-Lo, Belgium.
  3. *
  4. * See the LICENSE file for terms of use.
  5. */
  6. #include <stdlib.h>
  7. #include <boost/tokenizer.hpp>
  8. #include <Wt/WAbstractItemModel>
  9. #include <Wt/WString>
  10. #include "CsvUtil.h"
  11. void readFromCsv(std::istream& f, Wt::WAbstractItemModel *model,
  12. int numRows, bool firstLineIsHeaders)
  13. {
  14. int csvRow = 0;
  15. while (f) {
  16. std::string line;
  17. getline(f, line);
  18. if (f) {
  19. typedef boost::tokenizer<boost::escaped_list_separator<char> >
  20. CsvTokenizer;
  21. CsvTokenizer tok(line);
  22. int col = 0;
  23. for (CsvTokenizer::iterator i = tok.begin();
  24. i != tok.end(); ++i, ++col) {
  25. if (col >= model->columnCount())
  26. model->insertColumns(model->columnCount(),
  27. col + 1 - model->columnCount());
  28. if (firstLineIsHeaders && csvRow == 0)
  29. model->setHeaderData(col, boost::any(Wt::WString::fromUTF8(*i)));
  30. else {
  31. int dataRow = firstLineIsHeaders ? csvRow - 1 : csvRow;
  32. if (numRows != -1 && dataRow >= numRows)
  33. return;
  34. if (dataRow >= model->rowCount())
  35. model->insertRows(model->rowCount(),
  36. dataRow + 1 - model->rowCount());
  37. boost::any data;
  38. std::string s = *i;
  39. char *endptr;
  40. if (s.empty())
  41. data = boost::any();
  42. else {
  43. double d = strtod(s.c_str(), &endptr);
  44. if (*endptr == 0)
  45. data = boost::any(d);
  46. else
  47. data = boost::any(Wt::WString::fromUTF8(s));
  48. }
  49. model->setData(dataRow, col, data);
  50. }
  51. }
  52. }
  53. ++csvRow;
  54. }
  55. }