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.
 
 

127 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 = 0;
while (getline(file, line)) {
rowNum = rowNum + 1;
stringstream linestream(line);
string cell;
ZCSVCell csvCell;
csvCell.rowNum = rowNum;
int colNum = 0;
while (getline(linestream, cell, ',')) {
colNum = colNum + 1;
csvCell.colNum = colNum;
csvCell.data = cell;
csvData.push_back(csvCell);
}
csvData.push_back(csvCell);
}
// 找到最大行数
int maxRowNum = 0;
for (list<ZCSVCell>::iterator it = csvData.begin(); it != csvData.end(); it++) {
if (it->rowNum > maxRowNum) {
maxRowNum = it->rowNum;
}
}
// 找到最大列数
int maxColNum = 0;
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 "";
}
}
void ZCSV::dumpCSV(string filename) {
ofstream file;
file.open(filename, ios::out | ios::trunc);
// 找到最大行数
int maxRowNum = 0;
for (list<ZCSVCell>::iterator it = csvData.begin(); it != csvData.end(); it++) {
if (it->rowNum > maxRowNum) {
maxRowNum = it->rowNum;
}
}
// 找到最大列数
int maxColNum = 0;
for (list<ZCSVCell>::iterator it = csvData.begin(); it != csvData.end(); it++) {
if (it->colNum > maxColNum) {
maxColNum = it->colNum;
}
}
// 足个点插入数据
for (int i = 1; i <= maxRowNum; i++) {
for (int j = 1; j <= maxColNum; j++) {
ZCSVCell* cell = findCell(i, j);
if (cell != NULL) {
file << cell->data;
}
file << ",";
}
file << endl;
}
}