Wt examples  3.2.1
CsvUtil.C
Go to the documentation of this file.
1 #include <boost/tokenizer.hpp>
2 #include <boost/lexical_cast.hpp>
3 
4 #include <Wt/WAbstractItemModel>
5 #include <Wt/WString>
6 
7 #include "CsvUtil.h"
8 
9 void readFromCsv(std::istream& f, Wt::WAbstractItemModel *model,
10  int numRows, bool firstLineIsHeaders)
11 {
12  int csvRow = 0;
13 
14  while (f) {
15  std::string line;
16  getline(f, line);
17 
18  if (f) {
19  typedef boost::tokenizer<boost::escaped_list_separator<char> >
20  CsvTokenizer;
21  CsvTokenizer tok(line);
22 
23  int col = 0;
24  for (CsvTokenizer::iterator i = tok.begin();
25  i != tok.end(); ++i, ++col) {
26 
27  if (col >= model->columnCount())
28  model->insertColumns(model->columnCount(),
29  col + 1 - model->columnCount());
30 
31  if (firstLineIsHeaders && csvRow == 0)
32  model->setHeaderData(col, boost::any(Wt::WString::fromUTF8(*i)));
33  else {
34  int dataRow = firstLineIsHeaders ? csvRow - 1 : csvRow;
35 
36  if (numRows != -1 && dataRow >= numRows)
37  return;
38 
39  if (dataRow >= model->rowCount())
40  model->insertRows(model->rowCount(),
41  dataRow + 1 - model->rowCount());
42 
43  std::string s = *i;
44 
45  boost::any data;
46 
47  char *end;
48  int i = std::strtol(s.c_str(), &end, 10);
49  if (*end == 0)
50  data = boost::any(i);
51  else {
52  double d = std::strtod(s.c_str(), &end);
53  if (*end == 0)
54  data = boost::any(d);
55  else
56  data = boost::any(Wt::WString::fromUTF8(s));
57  }
58 
59  model->setData(dataRow, col, data);
60  }
61  }
62  }
63 
64  ++csvRow;
65  }
66 }

Generated on Mon May 28 2012 for the C++ Web Toolkit (Wt) by doxygen 1.8.1