Bitcoin ABC 0.30.7
P2P Digital Currency
csvmodelwriter.cpp
Go to the documentation of this file.
1// Copyright (c) 2011-2016 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <qt/csvmodelwriter.h>
6
7#include <QAbstractItemModel>
8#include <QFile>
9#include <QTextStream>
10
11CSVModelWriter::CSVModelWriter(const QString &_filename, QObject *parent)
12 : QObject(parent), filename(_filename), model(nullptr) {}
13
14void CSVModelWriter::setModel(const QAbstractItemModel *_model) {
15 this->model = _model;
16}
17
18void CSVModelWriter::addColumn(const QString &title, int column, int role) {
19 Column col;
20 col.title = title;
21 col.column = column;
22 col.role = role;
23
24 columns.append(col);
25}
26
27static void writeValue(QTextStream &f, const QString &value) {
28 QString escaped = value;
29 escaped.replace('"', "\"\"");
30 f << "\"" << escaped << "\"";
31}
32
33static void writeSep(QTextStream &f) {
34 f << ",";
35}
36
37static void writeNewline(QTextStream &f) {
38 f << "\n";
39}
40
42 QFile file(filename);
43 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
44 return false;
45 }
46 QTextStream out(&file);
47
48 int numRows = 0;
49 if (model) {
50 numRows = model->rowCount();
51 }
52
53 // Header row
54 for (int i = 0; i < columns.size(); ++i) {
55 if (i != 0) {
56 writeSep(out);
57 }
58 writeValue(out, columns[i].title);
59 }
60 writeNewline(out);
61
62 // Data rows
63 for (int j = 0; j < numRows; ++j) {
64 for (int i = 0; i < columns.size(); ++i) {
65 if (i != 0) {
66 writeSep(out);
67 }
68 QVariant data =
69 model->index(j, columns[i].column).data(columns[i].role);
70 writeValue(out, data.toString());
71 }
72 writeNewline(out);
73 }
74
75 file.close();
76
77 return file.error() == QFile::NoError;
78}
QList< Column > columns
CSVModelWriter(const QString &filename, QObject *parent=nullptr)
bool write()
Perform export of the model to CSV.
void setModel(const QAbstractItemModel *model)
void addColumn(const QString &title, int column, int role=Qt::EditRole)
const QAbstractItemModel * model
static void writeValue(QTextStream &f, const QString &value)
static void writeSep(QTextStream &f)
static void writeNewline(QTextStream &f)