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.

csvmodelwriter.cpp 1.8KB

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