/home/koen/project/wt/cvs/wt/examples/charts/CsvUtil.C

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           boost::any data;
00044           std::string s = *i;
00045 
00046           try {
00047             int i = boost::lexical_cast<int>(s);
00048             data = boost::any(i);
00049           } catch (boost::bad_lexical_cast&) {
00050             try {
00051               double d = boost::lexical_cast<double>(s);
00052               data = boost::any(d);
00053             } catch (boost::bad_lexical_cast&) {
00054               data = boost::any(Wt::WString::fromUTF8(s));
00055             }
00056           }
00057 
00058           model->setData(dataRow, col, data);
00059         }
00060       }
00061     }
00062 
00063     ++csvRow;
00064   }
00065 }

Generated on Fri Jul 25 17:05:59 2008 for Wt by doxygen 1.5.3