Save QtableData in csv file
-
I am facing a minor issue while saving data from QStandatdItemViewModel of TableView in a text file seperated by comma and newline.
The problem is if i dont update the model then the data is stored properly. But if i update any filed in the tableview the newline is skipped.Please help.
void MainWindow::mSaveTextFile() { // [Collect model data to QString] QString textData; int rows = pModel->rowCount(); int columns = pModel->columnCount(); qDebug() << rows<<" "<<columns; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { textData += pModel->data(pModel->index(i,j)).toString(); qDebug() <<textData<<endl; if(j == 0) textData += ", " ; // for .csv file format } textData += "\n"; // ( for new line segmentation) } // [Save to file] (header file <QFile> needed) // .txt QFile txtFile(sSaveFile); if(txtFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QTextStream out(&txtFile); out << textData; txtFile.close(); } }
-
I have added source code markers with the right icon above the edit window.
Your source looks for the newline character ok to me.
Odd is the check with j==0. This will work only for 2 columns. For other cols the output will be skipped.
I would try to use the debugger with some break points in the loop. Then you can check step by step.
-
my data is having 2 columns so my intention is to add " , " only after 1 column data. After 2nd column I want new line to be added.For this j==0 check is made.
Expected data:
Adam, 20
Charles, 40
Delta-F , 70
Falcon, 35Observed Output:
Adam, 20
Charles, 40Delta-F , 70
Falcon, 35This occurs only if i edit the field with value 40.
-
Do you see this output in the output file or with qDebug() you are using?
-
You are saving in binary format rather than text that's what's causing your problem (i.e. you have to open the file with the
QIODevice::Text
flag). you also have to escape special characters in the fields (what happens if there is a,
or a"
in the first column?)I have implemented this code: https://github.com/VSRonin/Qt-Model-Serialisation/tree/dev the documentation is not yet complete (hence it not being merged in the master branch) but the example should give you a stating point and if you struggle I'm happy to help
CsvModelSerialiser csvSave(pModel); QFile tempFile("TestSave.csv"); if(!csvSave.saveModel(&tempFile)) Q_ASSERT(false);