CSV檔案(可以轉換為Excel)的讀寫
阿新 • • 發佈:2019-01-18
有時候會碰到用C++讀寫Excel檔案的情況,我們可以通過讀寫CSV檔案,然後將CSV檔案轉換成Excel檔案進行。
經常需要一些配置資訊,在啟動的時候程式將這類資訊讀入記憶體中使用,CSV是個不錯的選擇,這裡提供一個CSV的讀寫類,預設將第一行當做欄位名,通過欄位名去讀寫內容
先看程式碼
CSVFile.h
- #ifndef __CSVFile_H__
- #define __CSVFile_H__
- #include <fstream>
- #include <string>
- #include <sstream>
-
#include <vector>
- class CSVFile
- {
- public:
- bool Open(bool bIsRead, constchar* strPath, constchar* strFilename);
- // 讀介面
- bool CSVReadNextRow();
- template<class T>
- bool CSVRead(constchar* strFieldName, T& data)
- {
-
if (m_nFileState != FILE_STATE_READ)
- {
- returnfalse;
- }
- int n = FindField(strFieldName);
- if (n == -1 || n >= m_CSVCurRow.size())
- {
- returnfalse;
- }
- std::stringstream ss;
- ss << m_CSVCurRow[n];
-
ss >> data;
- returntrue;
- }
- // 寫介面
- void CSVWriteNextRow();
- template<class T>
- bool CSVWrite(constchar* strFieldName, T data)
- {
- if (m_nFileState != FILE_STATE_WRITE)
- {
- returnfalse;
- }
- int n = FindField(strFieldName);
- if (n == -1)
- {
- returnfalse;
- }
- std::stringstream ss;
- ss << data;
- m_CSVCurRow[n] = ss.str();
- returntrue;
- }
- private:
- typedef std::vector<std::string> ROWVEC;
- void ReadCSVHead();
- void RowParse(constchar* strRow, int nSize, ROWVEC& result);
- int FindField(constchar* strRow);
- private:
- enum
- {
- FILE_STATE_NULL,
- FILE_STATE_READ,
- FILE_STATE_WRITE,
- };
- int m_nFileState;
- std::fstream m_CSVFile;
- ROWVEC m_CSVHead;
- ROWVEC m_CSVCurRow;
- };
- #endif // __CSVWriter_H__
CSVFile.cpp
- #include "CSVFile.h"
- #include <sstream>
- #include <assert.h>
- void CSVFile::ReadCSVHead()
- {
- char strHeadLine[4096];
- m_CSVFile.getline(strHeadLine, sizeof(strHeadLine));
- RowParse(strHeadLine, sizeof(strHeadLine), m_CSVHead);
- }
- void CSVFile::RowParse(constchar* strRow, int nSize, ROWVEC& result)
- {
- result.clear();
- bool bIsInWord = false;
- bool bIsHaveSpace = false;
- std::string strCurWorld;
- for (int i=0; i<nSize; i++)
- {
- char ch = strRow[i];
- if (ch == '\0')
- {
- if (i >= 1 && strRow[i-1] == ',')
- {
- strCurWorld = ' ';
- }
- break;
- }
- bool bIsAdd = true;
- switch (ch)
- {
- case',':
- {
- if (!bIsInWord)
- {
- // 一項結束
- result.push_back(strCurWorld);
- bIsInWord = false;
- bIsHaveSpace = false;
- strCurWorld = "";
- bIsAdd = false;
- }
- }
- break;
- case'"':
- {
- if (!bIsInWord)