-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCsvUtil.cpp
More file actions
71 lines (55 loc) · 1.51 KB
/
CsvUtil.cpp
File metadata and controls
71 lines (55 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* Copyright (C) 2008 Emweb bvba, Kessel-Lo, Belgium.
*
* See the LICENSE file for terms of use.
*/
#include <stdlib.h>
#include <boost/tokenizer.hpp>
#include <Wt/WAbstractItemModel.h>
#include <Wt/WString.h>
#include "CsvUtil.h"
void readFromCsv(std::istream& f, Wt::WAbstractItemModel *model,
int numRows, bool firstLineIsHeaders)
{
int csvRow = 0;
while (f) {
std::string line;
getline(f, line);
if (f) {
// Tokenize a single line
typedef boost::tokenizer<boost::escaped_list_separator<char> > CsvTokenizer;
CsvTokenizer tok(line);
// Loop through columns
int col = 0;
for (CsvTokenizer::iterator i = tok.begin(); i != tok.end(); ++i, ++col) {
if (col >= model->columnCount())
model->insertColumns(model->columnCount(),
col + 1 - model->columnCount());
if (firstLineIsHeaders && csvRow == 0)
model->setHeaderData(col, Wt::cpp17::any(Wt::WString(*i)));
else {
int dataRow = firstLineIsHeaders ? csvRow - 1 : csvRow;
if (numRows != -1 && dataRow >= numRows)
return;
if (dataRow >= model->rowCount())
model->insertRows(model->rowCount(),
dataRow + 1 - model->rowCount());
Wt::cpp17::any data;
std::string s = *i;
char* endptr;
if (s.empty())
data = Wt::cpp17::any();
else {
double d = strtod(s.c_str(), &endptr);
if (*endptr == 0)
data = Wt::cpp17::any(d);
else
data = Wt::cpp17::any(Wt::WString(s));
}
model->setData(dataRow, col, data);
}
} // end for loop
}
++csvRow;
}
}