2017-01-13 19:09:58 +01:00
|
|
|
|
#include "csvwriter.h"
|
|
|
|
|
|
|
|
|
|
|
|
CsvWriter::CsvWriter()
|
2017-02-04 11:53:20 +01:00
|
|
|
|
{}
|
|
|
|
|
|
|
|
|
|
|
|
CsvWriter::CsvWriter(QTextStream *output)
|
|
|
|
|
|
: m_output(output)
|
|
|
|
|
|
{}
|
2017-01-13 19:09:58 +01:00
|
|
|
|
|
2017-02-04 11:53:20 +01:00
|
|
|
|
void CsvWriter::setDestination(QTextStream *output)
|
|
|
|
|
|
{
|
|
|
|
|
|
m_output = output;
|
|
|
|
|
|
m_column = 0;
|
2017-01-13 19:09:58 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2017-02-04 11:53:20 +01:00
|
|
|
|
void CsvWriter::setSeperator(QChar ch)
|
|
|
|
|
|
{
|
|
|
|
|
|
m_seperator = ch;
|
|
|
|
|
|
}
|
2017-01-13 19:09:58 +01:00
|
|
|
|
|
2017-02-04 11:53:20 +01:00
|
|
|
|
void CsvWriter::setQuote(QChar ch)
|
|
|
|
|
|
{
|
|
|
|
|
|
m_quote = ch;
|
|
|
|
|
|
}
|
2017-01-13 19:09:58 +01:00
|
|
|
|
|
2017-02-04 11:53:20 +01:00
|
|
|
|
void CsvWriter::writeField(QString field)
|
|
|
|
|
|
{
|
|
|
|
|
|
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
|
2017-01-13 19:09:58 +01:00
|
|
|
|
// when quoted quotes need to be doubled to escape them
|
|
|
|
|
|
bool needs_quotes = false;
|
|
|
|
|
|
for (auto ch : field) {
|
|
|
|
|
|
if (ch == '\n' || ch == m_seperator || ch == m_quote) {
|
|
|
|
|
|
needs_quotes = true;
|
2017-02-04 11:53:20 +01:00
|
|
|
|
break;
|
2017-01-13 19:09:58 +01:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2017-02-04 11:53:20 +01:00
|
|
|
|
|
2017-01-13 19:09:58 +01:00
|
|
|
|
if (needs_quotes) {
|
2017-02-04 11:53:20 +01:00
|
|
|
|
out << m_quote;
|
|
|
|
|
|
for (auto ch : field) {
|
|
|
|
|
|
if (ch == m_quote)
|
|
|
|
|
|
out << m_quote;
|
|
|
|
|
|
out << ch;
|
|
|
|
|
|
}
|
|
|
|
|
|
out << m_quote;
|
|
|
|
|
|
}
|
|
|
|
|
|
else {
|
|
|
|
|
|
out << field;
|
|
|
|
|
|
}
|
|
|
|
|
|
++m_column;
|
|
|
|
|
|
}
|
2017-01-13 19:09:58 +01:00
|
|
|
|
|
|
|
|
|
|
|
2017-02-04 11:53:20 +01:00
|
|
|
|
void CsvWriter::nextRow()
|
|
|
|
|
|
{
|
|
|
|
|
|
QTextStream &out = *m_output;
|
|
|
|
|
|
out << '\n';
|
|
|
|
|
|
m_column = 0;
|
2017-01-13 19:09:58 +01:00
|
|
|
|
}
|
2017-02-04 11:53:20 +01:00
|
|
|
|
|