2016-12-31 19:01:21 +01:00
|
|
|
// Copyright (c) 2011-2016 The Bitcoin Core developers
|
2014-12-13 05:09:33 +01:00
|
|
|
// Distributed under the MIT software license, see the accompanying
|
2013-11-04 16:20:43 +01:00
|
|
|
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
|
|
|
|
2011-07-07 14:27:16 +02:00
|
|
|
#include "csvmodelwriter.h"
|
|
|
|
|
|
|
|
#include <QAbstractItemModel>
|
|
|
|
#include <QFile>
|
|
|
|
#include <QTextStream>
|
|
|
|
|
2016-09-09 13:43:29 +02:00
|
|
|
CSVModelWriter::CSVModelWriter(const QString &_filename, QObject *parent) :
|
2011-07-07 14:27:16 +02:00
|
|
|
QObject(parent),
|
2016-09-09 13:43:29 +02:00
|
|
|
filename(_filename), model(0)
|
2011-07-07 14:27:16 +02:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2016-09-09 13:43:29 +02:00
|
|
|
void CSVModelWriter::setModel(const QAbstractItemModel *_model)
|
2011-07-07 14:27:16 +02:00
|
|
|
{
|
2016-09-09 13:43:29 +02:00
|
|
|
this->model = _model;
|
2011-07-07 14:27:16 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
void CSVModelWriter::addColumn(const QString &title, int column, int role)
|
|
|
|
{
|
|
|
|
Column col;
|
|
|
|
col.title = title;
|
|
|
|
col.column = column;
|
|
|
|
col.role = role;
|
|
|
|
|
|
|
|
columns.append(col);
|
|
|
|
}
|
|
|
|
|
|
|
|
static void writeValue(QTextStream &f, const QString &value)
|
|
|
|
{
|
2012-05-11 20:17:09 +02:00
|
|
|
QString escaped = value;
|
|
|
|
escaped.replace('"', "\"\"");
|
|
|
|
f << "\"" << escaped << "\"";
|
2011-07-07 14:27:16 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
static void writeSep(QTextStream &f)
|
|
|
|
{
|
|
|
|
f << ",";
|
|
|
|
}
|
|
|
|
|
|
|
|
static void writeNewline(QTextStream &f)
|
|
|
|
{
|
|
|
|
f << "\n";
|
|
|
|
}
|
|
|
|
|
|
|
|
bool CSVModelWriter::write()
|
|
|
|
{
|
|
|
|
QFile file(filename);
|
|
|
|
if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
|
|
|
|
return false;
|
|
|
|
QTextStream out(&file);
|
|
|
|
|
2011-11-08 21:18:36 +01:00
|
|
|
int numRows = 0;
|
|
|
|
if(model)
|
|
|
|
{
|
|
|
|
numRows = model->rowCount();
|
|
|
|
}
|
2011-07-07 14:27:16 +02:00
|
|
|
|
|
|
|
// Header row
|
|
|
|
for(int i=0; i<columns.size(); ++i)
|
|
|
|
{
|
|
|
|
if(i!=0)
|
|
|
|
{
|
|
|
|
writeSep(out);
|
|
|
|
}
|
|
|
|
writeValue(out, columns[i].title);
|
|
|
|
}
|
|
|
|
writeNewline(out);
|
|
|
|
|
|
|
|
// Data rows
|
|
|
|
for(int j=0; j<numRows; ++j)
|
|
|
|
{
|
|
|
|
for(int i=0; i<columns.size(); ++i)
|
|
|
|
{
|
|
|
|
if(i!=0)
|
|
|
|
{
|
|
|
|
writeSep(out);
|
|
|
|
}
|
|
|
|
QVariant data = model->index(j, columns[i].column).data(columns[i].role);
|
|
|
|
writeValue(out, data.toString());
|
|
|
|
}
|
|
|
|
writeNewline(out);
|
|
|
|
}
|
|
|
|
|
|
|
|
file.close();
|
|
|
|
|
|
|
|
return file.error() == QFile::NoError;
|
|
|
|
}
|