Wt examples  3.3.1
CsvUtil.C
Go to the documentation of this file.
1 #include <fstream>
2 
3 #include <boost/tokenizer.hpp>
4 #include <boost/lexical_cast.hpp>
5 
6 #include <Wt/WAbstractItemModel>
7 #include <Wt/WStandardItemModel>
8 #include <Wt/WString>
9 
10 #include "CsvUtil.h"
11 
12 Wt::WStandardItemModel *csvToModel(const std::string& csvFile,
13  Wt::WObject *parent)
14 {
15  std::ifstream f(csvFile.c_str());
16 
17  if (f) {
18  Wt::WStandardItemModel *result = new Wt::WStandardItemModel(0, 0, parent);
19  readFromCsv(f, result);
20  return result;
21  } else
22  return 0;
23 }
24 
25 void readFromCsv(std::istream& f, Wt::WAbstractItemModel *model,
26  int numRows, bool firstLineIsHeaders)
27 {
28  int csvRow = 0;
29 
30  while (f) {
31  std::string line;
32  getline(f, line);
33 
34  if (f) {
35  typedef boost::tokenizer<boost::escaped_list_separator<char> >
36  CsvTokenizer;
37  CsvTokenizer tok(line);
38 
39  int col = 0;
40  for (CsvTokenizer::iterator i = tok.begin();
41  i != tok.end(); ++i, ++col) {
42 
43  if (col >= model->columnCount())
44  model->insertColumns(model->columnCount(),
45  col + 1 - model->columnCount());
46 
47  if (firstLineIsHeaders && csvRow == 0)
48  model->setHeaderData(col, boost::any(Wt::WString::fromUTF8(*i)));
49  else {
50  int dataRow = firstLineIsHeaders ? csvRow - 1 : csvRow;
51 
52  if (numRows != -1 && dataRow >= numRows)
53  return;
54 
55  if (dataRow >= model->rowCount())
56  model->insertRows(model->rowCount(),
57  dataRow + 1 - model->rowCount());
58 
59  std::string s = *i;
60 
61  boost::any data;
62 
63  char *end;
64  int i = std::strtol(s.c_str(), &end, 10);
65  if (*end == 0)
66  data = boost::any(i);
67  else {
68  double d = std::strtod(s.c_str(), &end);
69  if (*end == 0)
70  data = boost::any(d);
71  else
72  data = boost::any(Wt::WString::fromUTF8(s));
73  }
74 
75  model->setData(dataRow, col, data);
76  }
77  }
78  }
79 
80  ++csvRow;
81  }
82 }
virtual bool insertColumns(int column, int count, const WModelIndex &parent=WModelIndex())
Wt::WStandardItemModel * csvToModel(const std::string &csvFile, Wt::WObject *parent)
Definition: CsvUtil.C:12
static WString fromUTF8(const std::string &value, bool checkValid=false)
virtual bool insertRows(int row, int count, const WModelIndex &parent=WModelIndex())
virtual int rowCount(const WModelIndex &parent=WModelIndex()) const =0
virtual int columnCount(const WModelIndex &parent=WModelIndex()) const =0
virtual bool setHeaderData(int section, Orientation orientation, const boost::any &value, int role=EditRole)
void readFromCsv(std::istream &f, Wt::WAbstractItemModel *model, int numRows, bool firstLineIsHeaders)
Utility function that reads a model from a CSV file.
Definition: CsvUtil.C:25
virtual bool setData(const WModelIndex &index, const boost::any &value, int role=EditRole)

Generated on Wed Jun 11 2014 for the C++ Web Toolkit (Wt) by doxygen 1.8.7