Wt examples: charts/CsvUtil.C Source File

Wt examples 4.10.4

Loading...
Searching...
No Matches
CsvUtil.C
Go to the documentation of this file.
1/*
2 * Copyright (C) 2008 Emweb bv, Herent, 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.h>
11#include <Wt/WString.h>
12
13#include "CsvUtil.h"
14
15 void 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, Wt::cpp17::any(Wt::WString(*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 Wt::cpp17::any data;
50 std::string s = *i;
51
52 char *endptr;
53
54 if (s.empty())
55 data = Wt::cpp17::any();
56 else {
57 double d = strtod(s.c_str(), &endptr);
58 if (*endptr == 0)
59 data = Wt::cpp17::any(d);
60 else
61 data = Wt::cpp17::any(Wt::WString(s));
62 }
63
64 model->setData(dataRow, col, data);
65 }
66 }
67 }
68
69 ++csvRow;
70 }
71}
readFromCsv
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
CsvUtil.h