Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

Simple Qt based CSV String Builder

From Wiki
Jump to: navigation, search
Article Metadata
Tested with
Devices(s): Emulator / desktop / device
Compatibility
Platform(s): All Qt Supported
Symbian
Article
Keywords: QStringList
Created: skumar_rao (24 Nov 2010)
Last edited: hamishwillee (11 Oct 2012)

CSV or comma-separated values, is the simplest for of data storage (sort of basic Database) where each record is represented in the form of a lined values separated by a ",". CSV is a simple file format that is widely supported, so it is often used to move tabular data between different computer programs that support the format. For example, a CSV file might be used to transfer information from a database program to a spreadsheet.

In this article we will try creating a very simple Qt based CSV builder that will help us in saving out data to a file very easy and readable.

csvbuilder.h

#include <QtCore>
 
class CSVBuilder : public QObject
{
Q_OBJECT
public:
CSVBuilder();
~CSVBuilder();
 
QString currentLine();
QString build();
void push(QString cell);
void newLine();
 
private:
QStringList* m_currentLine;
QList<QStringList*>* m_lines;
};

csvbuilder.cpp

#define KDefaultDelimiter ','
#define KDefaultEscapeChar '"'
#define KDefaultNewLine "\n"
 
CSVBuilder::CSVBuilder() {
m_currentLine = new QStringList;
m_lines = new QList<QStringList*>;
}
 
CSVBuilder::~CSVBuilder() {
 
}
 
void CSVBuilder::push(QString cell) {
if(cell.contains(KDefaultEscapeChar) || cell.contains(KDefaultNewLine)
|| cell.contains(KDefaultDelimiter)) {
m_currentLine->append(cell.replace(KDefaultNewLine,
QString(KDefaultEscapeChar) + KDefaultEscapeChar)
.prepend(KDefaultEscapeChar)
.append(KDefaultEscapeChar));
} else {
m_currentLine->append(cell);
}
}
 
QString CSVBuilder::currentLine() {
return m_currentLine->join(",");
}
 
QString CSVBuilder::build() {
if (!m_currentLine->isEmpty()) {
newLine();
}
QString final;
foreach (QStringList *line, *m_lines) {
final.append(line->join(","));
final.append(KDefaultNewLine);
}
return final;
}
 
void CSVBuilder::newLine() {
m_lines->append(m_currentLine);
m_currentLine = new QStringList;
}

File:TestCSVBuilder.zip

--skumar_rao 17:53, 23 November 2010 (UTC)

This page was last modified on 11 October 2012, at 01:18.
116 page views in the last 30 days.
×