Go to the documentation of this file.00001 #include <boost/tokenizer.hpp>
00002 #include <boost/lexical_cast.hpp>
00003
00004 #include <Wt/WAbstractItemModel>
00005 #include <Wt/WString>
00006
00007 #include "CsvUtil.h"
00008
00009 void readFromCsv(std::istream& f, Wt::WAbstractItemModel *model,
00010 int numRows, bool firstLineIsHeaders)
00011 {
00012 int csvRow = 0;
00013
00014 while (f) {
00015 std::string line;
00016 getline(f, line);
00017
00018 if (f) {
00019 typedef boost::tokenizer<boost::escaped_list_separator<char> >
00020 CsvTokenizer;
00021 CsvTokenizer tok(line);
00022
00023 int col = 0;
00024 for (CsvTokenizer::iterator i = tok.begin();
00025 i != tok.end(); ++i, ++col) {
00026
00027 if (col >= model->columnCount())
00028 model->insertColumns(model->columnCount(),
00029 col + 1 - model->columnCount());
00030
00031 if (firstLineIsHeaders && csvRow == 0)
00032 model->setHeaderData(col, boost::any(Wt::WString::fromUTF8(*i)));
00033 else {
00034 int dataRow = firstLineIsHeaders ? csvRow - 1 : csvRow;
00035
00036 if (numRows != -1 && dataRow >= numRows)
00037 return;
00038
00039 if (dataRow >= model->rowCount())
00040 model->insertRows(model->rowCount(),
00041 dataRow + 1 - model->rowCount());
00042
00043 std::string s = *i;
00044
00045 boost::any data;
00046
00047 char *end;
00048 int i = std::strtol(s.c_str(), &end, 10);
00049 if (*end == 0)
00050 data = boost::any(i);
00051 else {
00052 double d = std::strtod(s.c_str(), &end);
00053 if (*end == 0)
00054 data = boost::any(d);
00055 else
00056 data = boost::any(Wt::WString::fromUTF8(s));
00057 }
00058
00059 model->setData(dataRow, col, data);
00060 }
00061 }
00062 }
00063
00064 ++csvRow;
00065 }
00066 }