[C++] 纯文本查看 复制代码
//Export table in CSV. TODO: Display a dialog where the user choose what column to export and in which encoding
bool ExportCSV(dsint rows, dsint columns, std::vector<QString> headers, std::function<QString(dsint, dsint)> getCellContent)
{
BrowseDialog browse(nullptr, QApplication::translate("ExportCSV", "Export data in CSV format"), QApplication::translate("ExportCSV", "Enter the CSV file name to export"), QApplication::translate("ExportCSV", "CSV files (*.csv);;All files (*.*)"), QApplication::applicationDirPath() + QDir::separator() + "db", true);
browse.setWindowIcon(DIcon("database-export.png"));
if(browse.exec() == QDialog::Accepted)
{
FILE* csv;
bool utf16;
csv = _wfopen(browse.path.toStdWString().c_str(), L"wb");
if(csv == NULL)
{
GuiAddLogMessage(QApplication::translate("ExportCSV", "CSV export error\n").toUtf8().constData());
return false;
}
else
{
duint setting;
if(BridgeSettingGetUint("Misc", "Utf16LogRedirect", &setting))
utf16 = !!setting;
else
utf16 = false;
if(utf16 && ftell(csv) == 0)
{
unsigned short BOM = 0xfeff;
fwrite(&BOM, 2, 1, csv);
}
dsint row, column;
QString text;
QString cell;
if(headers.size() > 0)
{
for(column = 0; column < columns; column++)
{
cell = headers.at(column);
if(cell.contains('"') || cell.contains(',') || cell.contains('\r') || cell.contains('\n'))
{
if(cell.contains('"'))
cell = cell.replace("\"", "\"\"");
cell = "\"" + cell + "\"";
}
if(column != columns - 1)
cell = cell + ",";
text = text + cell;
}
if(utf16)
{
text = text + "\r\n";
if(!fwrite(text.utf16(), text.length(), 2, csv))
{
fclose(csv);
GuiAddLogMessage(QApplication::translate("ExportCSV", "CSV export error\n").toUtf8().constData());
return false;
}
}
else
{
text = text + "\n";
QByteArray utf8;
utf8 = text.toUtf8();
if(!fwrite(utf8.constData(), utf8.size(), 1, csv))
{
fclose(csv);
GuiAddLogMessage(QApplication::translate("ExportCSV", "CSV export error\n").toUtf8().constData());
return false;
}
}
}
for(row = 0; row < rows; row++)
{
text.clear();
for(column = 0; column < columns; column++)
{
cell = getCellContent(row, column);
if(cell.contains('"') || cell.contains(',') || cell.contains('\r') || cell.contains('\n'))
{
if(cell.contains('"'))
cell = cell.replace("\"", "\"\"");
cell = "\"" + cell + "\"";
}
if(column != columns - 1)
cell = cell + ",";
text = text + cell;
}
if(utf16)
{
text = text + "\r\n";
if(!fwrite(text.utf16(), text.length(), 2, csv))
{
fclose(csv);
GuiAddLogMessage(QApplication::translate("ExportCSV", "CSV export error\n").toUtf8().constData());
return false;
}
}
else
{
text = text + "\n";
QByteArray utf8;
utf8 = text.toUtf8();
if(!fwrite(utf8.constData(), utf8.size(), 1, csv))
{
fclose(csv);
GuiAddLogMessage(QApplication::translate("ExportCSV", "CSV export error\n").toUtf8().constData());
return false;
}
}
}
fclose(csv);
GuiAddLogMessage(QApplication::translate("ExportCSV", "Saved CSV data at %1\n").arg(browse.path).toUtf8().constData());
return true;
}
}
else
return false;
}