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