1)创建CRow类,用来描述每一行的记录
class CRow { public: CRow(CStringArray* row); int getColumnCount(void); CString getColumn(int i); private: CStringArray* m_row; }; CRow::CRow(CStringArray* row) { m_row = row; } int CRow::getColumnCount(void) { return m_row->GetCount(); } CString CRow::getColumn(int i) { return m_row->GetAt(i); }
2)创建CSheet类,用来描述一张表格
class CSheet { public: CSheet(void); ~CSheet(void); int loadFrom(std::ifstream& in); int getRowCount(void); CRow getRow(int i); private: CTypedPtrArray<CPtrArray, CStringArray*> m_rows; }; CSheet::CSheet(void) { } CSheet::~CSheet(void) { for (int i = 0; i<m_rows.GetCount(); i++) { delete m_rows.GetAt(i); } } int CSheet::loadFrom(std::ifstream& in) { int lines = 0; while(!in.eof()) { //读取其中一行 char line[256] = {0}; in.getline(line, 255); CString s = /*(CString)*/static_cast<CString>(line); //空白行则跳过 if (s.IsEmpty()) continue; //#为注释标记,跳过 if (s[0]=='#') continue; CStringArray* pRow = new CStringArray(); int i = 0; CString token = s.Tokenize(_T(",/t"), i); while (token!=_T("")) { pRow->Add(token); token = s.Tokenize(_T(",/t"), i); } m_rows.Add(pRow); lines++; } return lines; } int CSheet::getRowCount(void) { return m_rows.GetCount(); } CRow CSheet::getRow(int i) { return CRow(m_rows.GetAt(i)); }
3)测试程序
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { CSheet csvSheet; //打开csv文件 ifstream in("test.csv"); //加载至CSheet csvSheet.loadFrom(in); for (int i=0; i< csvSheet.getRowCount(); i++) { _tprintf(_T("[%02d] "), i); //获取制定行 CRow row = csvSheet.getRow(i); for (int j = 0; j< row.getColumnCount(); j++) { //获取指定列 CString s = row.getColumn(j); _tprintf(_T("%s|"), s); } _tprintf(_T("/r/n"), i); } return 0; }
test.csv
seconds,I_28,I_32,I_40,I_44,Total 7,0.321661,0.055679,0.004433,0.002650,0.005127 19,0.321527,0.055858,0.004424,0.002551,0.007007 34,0.321727,0.055934,0.004410,0.002569,0.006929 49,0.320924,0.055955,0.004403,0.002587,0.007055 64,0.324028,0.056220,0.004396,0.002534,0.006981 79,0.323823,0.056429,0.004431,0.002487,0.007047 94,0.323488,0.056333,0.004435,0.002460,0.007033 6,0.335632,0.061383,0.004633,0.000451,0.005494 18,0.334367,0.061270,0.004644,0.000437,0.007521 33,0.336057,0.061422,0.004565,0.000434,0.007521 48,0.335492,0.061543,0.004590,0.000470,0.007572 63,0.334581,0.061120,0.004597,0.000486,0.007565 78,0.317442,0.057566,0.004406,0.000954,0.007526 93,0.317904,0.057331,0.004358,0.001161,0.007559 108,0.316974,0.057049,0.004335,0.000964,0.007530 123,0.316575,0.057063,0.004367,0.001134,0.007509 138,0.316878,0.057147,0.004379,0.001189,0.007533 153,0.317506,0.057140,0.004388,0.001358,0.007585 168,0.318439,0.057360,0.004360,0.001171,0.007546 183,0.317303,0.057232,0.004410,0.001396,0.007586 198,0.318175,0.057246,0.004365,0.001165,0.007581 213,0.317807,0.057303,0.004328,0.001411,0.007519 228,0.317576,0.057247,0.004396,0.001353,0.007517