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