Completed the implementation of the CsvWriter for use with Copy and Export.

This commit is contained in:
Eelke Klein 2017-02-04 11:53:20 +01:00
parent 7a22b4cbea
commit 798f8f51b9
2 changed files with 54 additions and 20 deletions

View file

@ -1,30 +1,64 @@
#include "csvwriter.h" #include "csvwriter.h"
CsvWriter::CsvWriter() CsvWriter::CsvWriter()
{ {}
CsvWriter::CsvWriter(QTextStream *output)
: m_output(output)
{}
void CsvWriter::setDestination(QTextStream *output)
{
m_output = output;
m_column = 0;
} }
void CsvWriter::setSeperator(QChar ch)
{
m_seperator = ch;
}
//int complexField = (strchr(field, csvWriter->delimiter_) || strchr(field, '\n') || strchr(field, '\"')) ? 1 : 0; void CsvWriter::setQuote(QChar ch)
{
m_quote = ch;
}
void CsvWriter::writeField(QString field) { void CsvWriter::writeField(QString field)
// if field contains any of seperator quote or newline then it needs to be quoted {
QTextStream &out = *m_output;
if (m_column > 0) {
out << m_seperator;
}
// if field contains any of seperator, quote or newline then it needs to be quoted
// when quoted quotes need to be doubled to escape them // when quoted quotes need to be doubled to escape them
bool needs_quotes = false; bool needs_quotes = false;
int new_len = field.length();
for (auto ch : field) { for (auto ch : field) {
if (ch == m_quote) {
++new_len;
}
if (ch == '\n' || ch == m_seperator || ch == m_quote) { if (ch == '\n' || ch == m_seperator || ch == m_quote) {
needs_quotes = true; needs_quotes = true;
break;
}
}
}
}
if (needs_quotes) { if (needs_quotes) {
new_len += 2; out << m_quote;
for (auto ch : field) {
if (ch == m_quote)
out << m_quote;
out << ch;
}
out << m_quote;
}
else {
out << field;
}
++m_column;
}
void CsvWriter::nextRow()
{
QTextStream &out = *m_output;
out << '\n';
m_column = 0;
} }
}

View file

@ -2,22 +2,22 @@
#define CSVWRITER_H #define CSVWRITER_H
#include <ostream> #include <ostream>
#include <QFileDevice> #include <QTextStream>
class CsvWriter { class CsvWriter {
public: public:
CsvWriter(); CsvWriter();
void setDestination(QFileDevice *output); explicit CsvWriter(QTextStream *output);
void setDestination(QString filename); void setDestination(QTextStream *output);
void setSeperator(QChar ch); void setSeperator(QChar ch);
void setQuote(QChar ch);
void writeField(QString field); void writeField(QString field);
void nextLine(); void nextRow();
private: private:
QChar m_seperator = ','; QChar m_seperator = ',';
QChar m_quote = '\''; QChar m_quote = '"';
QTextStream *m_output = nullptr;
QFileDevice *m_output = nullptr; int m_column = 0;
}; };
#endif // CSVWRITER_H #endif // CSVWRITER_H