Wt examples 3.3.12
CsvUtil.C
Go to the documentation of this file.
1/*
2 * Copyright (C) 2008 Emweb bvba, Kessel-Lo, Belgium.
3 *
4 * See the LICENSE file for terms of use.
5 */
6
7#include <stdlib.h>
8#include <boost/tokenizer.hpp>
9
10#include <Wt/WAbstractItemModel>
11#include <Wt/WString>
12
13#include "CsvUtil.h"
14
15void readFromCsv(std::istream& f, Wt::WAbstractItemModel *model,
16 int numRows, bool firstLineIsHeaders)
17{
18 int csvRow = 0;
19
20 while (f) {
21 std::string line;
22 getline(f, line);
23
24 if (f) {
25 typedef boost::tokenizer<boost::escaped_list_separator<char> >
26 CsvTokenizer;
27 CsvTokenizer tok(line);
28
29 int col = 0;
30 for (CsvTokenizer::iterator i = tok.begin();
31 i != tok.end(); ++i, ++col) {
32
33 if (col >= model->columnCount())
34 model->insertColumns(model->columnCount(),
35 col + 1 - model->columnCount());
36
37 if (firstLineIsHeaders && csvRow == 0)
38 model->setHeaderData(col, boost::any(Wt::WString::fromUTF8(*i)));
39 else {
40 int dataRow = firstLineIsHeaders ? csvRow - 1 : csvRow;
41
42 if (numRows != -1 && dataRow >= numRows)
43 return;
44
45 if (dataRow >= model->rowCount())
46 model->insertRows(model->rowCount(),
47 dataRow + 1 - model->rowCount());
48
49 boost::any data;
50 std::string s = *i;
51
52 char *endptr;
53
54 if (s.empty())
55 data = boost::any();
56 else {
57 double d = strtod(s.c_str(), &endptr);
58 if (*endptr == 0)
59 data = boost::any(d);
60 else
61 data = boost::any(Wt::WString::fromUTF8(s));
62 }
63
64 model->setData(dataRow, col, data);
65 }
66 }
67 }
68
69 ++csvRow;
70 }
71}
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:15
virtual bool insertColumns(int column, int count, const WModelIndex &parent=WModelIndex())
virtual bool setHeaderData(int section, Orientation orientation, const boost::any &value, int role=EditRole)
virtual bool setData(const WModelIndex &index, const boost::any &value, int role=EditRole)
virtual int rowCount(const WModelIndex &parent=WModelIndex()) const=0
virtual bool insertRows(int row, int count, const WModelIndex &parent=WModelIndex())
virtual int columnCount(const WModelIndex &parent=WModelIndex()) const=0
static WString fromUTF8(const std::string &value, bool checkValid=false)

Generated on Fri May 17 2024 for the C++ Web Toolkit (Wt) by doxygen 1.9.8