Bitcoin ABC  0.22.13
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 
11 CSVModelWriter::CSVModelWriter(const QString &_filename, QObject *parent)
12  : QObject(parent), filename(_filename), model(nullptr) {}
13 
14 void CSVModelWriter::setModel(const QAbstractItemModel *_model) {
15  this->model = _model;
16 }
17 
18 void 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 
27 static void writeValue(QTextStream &f, const QString &value) {
28  QString escaped = value;
29  escaped.replace('"', "\"\"");
30  f << "\"" << escaped << "\"";
31 }
32 
33 static void writeSep(QTextStream &f) {
34  f << ",";
35 }
36 
37 static 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 }
void addColumn(const QString &title, int column, int role=Qt::EditRole)
QList< Column > columns
static void writeValue(QTextStream &f, const QString &value)
static void writeSep(QTextStream &f)
CSVModelWriter(const QString &filename, QObject *parent=nullptr)
const QAbstractItemModel * model
void setModel(const QAbstractItemModel *model)
static void writeNewline(QTextStream &f)
bool write()
Perform export of the model to CSV.