我希望使用C++和Qt应用程序和UI框架创建一个csv文件。是否有专门用于csv文件的库?
尝试使用qtcsv库来读写CSV文件。例如:
#include <QList>
#include <QStringList>
#include <QDir>
#include <QDebug>
#include "qtcsv/stringdata.h"
#include "qtcsv/reader.h"
#include "qtcsv/writer.h"
int main()
{
// prepare data that you want to save to csv-file
QStringList strList;
strList << "one" << "two" << "three";
QtCSV::StringData strData;
strData.addRow(strList);
strData.addEmptyRow();
strData << strList << "this is the last row";
// write to file
QString filePath = QDir::currentPath() + "/test.csv";
QtCSV::Writer::write(filePath, strData);
// read data from file
QList<QStringList> readData = QtCSV::Reader::readToList(filePath);
for ( int i = 0; i < readData.size(); ++i )
{
qDebug() << readData.at(i).join(",");
}
return 0;
}
QStringList strList;
strList << "one" << "two" << "three" << "with,comma";
,但是在文件中得到的是one,two,three,with,comma
而不是one,two,three,"with,comma"
,我是正确使用它还是库无法处理这么简单的事情? - Jablonski使用 QxtCsvModel
QxtCsvModel [libqxt.bitbucket.org] 类为 CSV 文件提供了一个 QAbstractTableModel [qt-project.org]。这可能是最简单的读写 csv 文件的方法,而无需将 csv 格式解析为 qt 可以理解的内容。只需要使用一行代码即可,例如以下代码读取 csv 文件:
csvmodel->setSource(fileName);
只是写CSV文件吗?虽然谷歌可能会显示一些CSV库,但你没有找到的可能原因是它太简单了。记住,CSV只是逗号分隔值。
要实现它,请使用任何手段编写文本文件(std :: ofstream,QFile,QTextStream)并执行以下操作:
foreach record
{
foreach value in record
{
write "\"" + escape(value) + "\""
if not last value in record
{
write ","
}
}
write "\n"
}
escape (value)
{
replace each "\"" with "\"\""
}