You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

130 lines
2.7 KiB

#include "zcsv.hpp"
using namespace std;
using namespace iflytop;
ZCSV::ZCSV() {}
bool ZCSV::parseCSV(string filename) {
csvData.clear();
ifstream file(filename);
string line;
if (!file.is_open()) {
return false;
}
int rowNum = -1;
while (getline(file, line)) {
rowNum = rowNum + 1;
stringstream linestream(line);
string cell;
ZCSVCell csvCell;
csvCell.rowNum = rowNum;
int colNum = -1;
while (getline(linestream, cell, ',')) {
colNum = colNum + 1;
csvCell.colNum = colNum;
csvCell.data = cell;
csvData.push_back(csvCell);
}
csvData.push_back(csvCell);
}
// 找到最大行数
int maxRowNum = -1;
for (list<ZCSVCell>::iterator it = csvData.begin(); it != csvData.end(); it++) {
if (it->rowNum > maxRowNum) {
maxRowNum = it->rowNum;
}
}
// 找到最大列数
int maxColNum = -1;
for (list<ZCSVCell>::iterator it = csvData.begin(); it != csvData.end(); it++) {
if (it->colNum > maxColNum) {
maxColNum = it->colNum;
}
}
m_maxRowNum = maxRowNum;
m_maxColNum = maxColNum;
return true;
}
ZCSVCell* ZCSV::findCell(int rowNum, int colNum) {
for (list<ZCSVCell>::iterator it = csvData.begin(); it != csvData.end(); it++) {
if (it->rowNum == rowNum && it->colNum == colNum) {
return &(*it);
}
}
return NULL;
}
void ZCSV::setdata(int rowNum, int colNum, string data) {
ZCSVCell* cell = findCell(rowNum, colNum);
if (cell != NULL) {
cell->data = data;
} else {
ZCSVCell newCell;
newCell.rowNum = rowNum;
newCell.colNum = colNum;
newCell.data = data;
if (rowNum > m_maxRowNum) {
m_maxRowNum = rowNum;
}
if (colNum > m_maxColNum) {
m_maxColNum = colNum;
}
csvData.push_back(newCell);
}
}
string ZCSV::getdata(int rowNum, int colNum) {
ZCSVCell* cell = findCell(rowNum, colNum);
if (cell != NULL) {
return cell->data;
} else {
return "";
}
}
int ZCSV::findCol(string key) {
int colNum = -1;
for (int i = 0; i <= m_maxColNum; i++) {
ZCSVCell* cell = findCell(0, i);
if (cell != NULL && cell->data == key) {
colNum = i;
break;
}
}
return colNum;
}
bool ZCSV::isColExist(string key) {
int colNum = findCol(key);
if (colNum != -1) {
return true;
}
return false;
}
string ZCSV::getData(string key, int rowNum) {
int colNum = findCol(key);
if (colNum == -1) {
return "";
}
return getdata(rowNum, colNum);
}
vector<string> ZCSV::getRowKeys() {
vector<string> keys;
for (int i = 0; i <= m_maxColNum; i++) {
ZCSVCell* cell = findCell(0, i);
if (cell != NULL) {
keys.push_back(cell->data);
}
}
return keys;
}