32、Qt读写csv文件
一、写入
QString fileName = QFileDialog::getSaveFileName(this, "写入", "/untitled.csv", tr("Files (*.csv)"));
if(fileName.isEmpty())
{
QMessageBox::warning(this, "提示", "文件名不能为空", QMessageBox::Ok);
return;
}
QFile file(fileName);
bool ret = file.open(QIODevice::WriteOnly);
if(!ret)
{
QMessageBox::warning(this, "提示", QString("打开文件失败: %1").arg(file.errorString()), QMessageBox::Ok);
return;
}
QString conTents;
//表头
conTents += "姓名";
conTents += ",";
conTents += "年龄";
conTents += ",";
conTents += "时间";
conTents += "\n";
conTents += "张三";
conTents += ",";
conTents += "23";
conTents += ",";
QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz").replace(" ", "-"); //有空格会导致年月日被省略
conTents += time;
conTents += "\n";
conTents += "李四";
conTents += ",";
conTents += "24";
conTents += ",";
time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz").replace(" ", "-"); //有空格会导致年月日被省略
conTents += time;
conTents += "\n";
conTents += "王五";
conTents += ",";
conTents += "25";
conTents += ",";
time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz").replace(" ", "-"); //有空格会导致年月日被省略
conTents += time;
conTents += "\n";
QByteArray baSave = QString(conTents).toLocal8Bit(); //格式转换
file.write(baSave.data());
file.close();
写入好的文件内容如下:
二、读取
void MainWindow::on_readPushButton_clicked()
{
QString fileName = QFileDialog::getOpenFileName(this, "读取", "", tr("File (*.csv)"));
QFile file(fileName);
if(file.open(QIODevice::ReadOnly)) //只读方式打开文件
{
while(!file.atEnd())
{
QString strLine = GetCorrectUnicode(file.readLine()); //格式转换
strLine.remove("\n"); //去掉结尾换行符号
QStringList strLineList = strLine.split(",");
if(strLineList.size() > 1)
{
qDebug() << strLineList.at(0) << strLineList.at(1) << strLineList.at(2);
}
}
file.close();
}
}
QString MainWindow::GetCorrectUnicode(const QByteArray &ba)
{
// state用于保存转换状态,它的成员invalidChars,可用来判断是否转换成功
// 如果转换成功,则值为0,如果值大于0,则说明转换失败
QTextCodec::ConverterState state;
// 先尝试使用utf-8的方式把QByteArray转换成QString
QString text = QTextCodec::codecForName("UTF-8")->toUnicode(ba.constData(), ba.size(), &state);
// 如果转换时无效字符数量大于0,说明编码格式不对
if (state.invalidChars > 0)
{
// 再尝试使用GBK的方式进行转换,一般就能转换正确(当然也可能是其它格式,但比较少见了)
text = QTextCodec::codecForName("GBK")->toUnicode(ba);
}
return text;
}
读取的内容如下: