Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Reading Data from CSV FILE

Reading Data from CSV FILE

Scheduled Pinned Locked Moved General and Desktop
7 Posts 6 Posters 44.6k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • I Offline
    I Offline
    Indrajeet
    wrote on 17 Jun 2011, 09:09 last edited by
    #1

    HI All

    I am trying to read data from csv file and put data into QTableWidget.
    Following is my File read code

    @
    QFile f("Book1.csv");
    if (f.open(QIODevice::ReadOnly))
    {
    //file opened successfully
    QString data;
    data = f.readAll();
    QStringList vals = data.split(',');
    f.close();
    }
    This is my code where i try to add data from vals into Table Widget

    for (int row = 0; row < iRowCount; row++ )
    {
    for (int col = 0; col < iColCount; col++)
    {
    QTableWidgetItem *temp = new QTableWidgetItem(lstData[row] );
    table->setItem( col, row, temp );
    }
    }
    @

    Problem I am facing
    In table it is adding 2 values in single cell.

    [EDIT: code formatting, please wrap in @-tags, Volker]

    1 Reply Last reply
    0
    • K Offline
      K Offline
      koahnig
      wrote on 17 Jun 2011, 09:15 last edited by
      #2

      You should embrace your code snippets in '@'. Otherwise nobody can read it.

      Vote the answer(s) that helped you to solve your issue(s)

      1 Reply Last reply
      0
      • G Offline
        G Offline
        goetz
        wrote on 17 Jun 2011, 10:13 last edited by
        #3

        First, please format your code nicely. Please wrap it in @-tags or use the code button in the editor. Then indent it correctly, otherwise the code is completely unreadable and you are very likely to not get an answer at all. I've done this for you, as you're new to the forum and you might not have known that yet. But pleas keep it in mind for your subsequent posts.

        To your actual problem:
        In the first part you read the contents of the complete file (readAll) and split that by commas. This way you get one single huge line containing all the values. You should read the file line by line (using QTextStream and readLine()) and split the single lines.

        For the second part, I see no connection to the first at all.

        Please be aware that parsing a CSV file not just splitting at a comma! The values will be enclosed in quotes (") if they contain a comma and if a value contains a comma and a quote it's becoming even more complicated.

        http://www.catb.org/~esr/faqs/smart-questions.html

        1 Reply Last reply
        0
        • S Offline
          S Offline
          solareclectic
          wrote on 18 Jun 2011, 06:07 last edited by
          #4

          First, if you know the data that will be coming in your CSVs, go ahead and .split(","), it is a perfectly acceptible expedient for in-house tools. I process thousands of CSV files that are all columns of numbers or rigidly defined string values.

          Secondly, proper handling of CSV is, as Volker noted, a complicated task. If your goal is to produce a robust CSV handler, then, by all means dive in and do a good job. But, if you just want the data out of a CSV into your app, then don't reinvent a complex solution; use this very good implementation to access a CSV in a very Qt way -- implemented as a QAbstractItemModel:
          http://dev.libqxt.org/libqxt/wiki/Home

          Additionally, especially if I am doing _any_thing at all with the data in the table, or, even if I'm not I tend to use Qt's models and views - I find it very orderly it keeps me from getting tangled up in keeping track of what row or column I'm supposed to be working on now.

          Here are some salient snips from one of my CSV processors...

          in constructor...
          @

          MyModel = new QStandardItemModel();
          //this code actually had used a QSqlTableModel
          //QStandardItemModel is simple
          //actually, anything derived from QAbstractItemModel will work

          ui->ModelView->setModel(MyModel);
          ui->ModelView->show();
          

          //actually, and this is important
          //if you were using libQxt's QxtCsvModel Class, you'd be done now.
          // http://libqxt.bitbucket.org/doc/0.6/qxtcsvmodel.html#details

          //but let's proceed for fun, anyway..
          //I found it convenient to put this QRecord on the stack, and just keep reusing it later
          tempQRecord.append(QSqlField("City",QVariant::String));
          tempQRecord.append(QSqlField("Region",QVariant::String));
          tempQRecord.append(QSqlField("Country",QVariant::String));
          // many more.....

          @

          Sometimes I read the whole file (line by line) into a QList<QStringList>,
          but here I just process it line by line
          @void MainWindow::processCSVFile(QString filename)
          {
          QFile file(filename);
          ui->statusBar->showMessage(filename);
          if (file.open(QIODevice::ReadOnly | QIODevice::Text))
          {
          while (!file.atEnd())
          {
          QString line = file.readLine();
          processLineFromCSV(line);
          ui->progressBar->setValue(++CurrentLine);
          }
          file.close();
          }
          }
          @

          Split each line and put the string into a QField
          which goes into QRecord
          and finally, inset into the Model

          @
          void MainWindow::processLineFromCSV(QString line)
          {
          QStringList strings = line.split(",");
          tempQRecord.setValue("City",strings.value(1));
          tempQRecord.setValue("Region",strings.value(2));
          // many more...
          MyModel->insertRecord(-1,tempQRecord);
          }@

          Maybe it seems heavy. But the pattern is easy and repeatable --
          and everything ends up exactly where it is supposed to.

          One last thing: I left references in the code where I
          update progress bars and status bars.
          -- this is soooooo helpful when you are batch processing a 1000 files of 8000 lines each.

          1 Reply Last reply
          0
          • J Offline
            J Offline
            jim_kaiser
            wrote on 18 Jun 2011, 06:39 last edited by
            #5

            @solarelectric: That's an interesting library! Thanks for the post.. I see some other cool features too.. JSON support!

            1 Reply Last reply
            0
            • I Offline
              I Offline
              Indrajeet
              wrote on 18 Jun 2011, 09:36 last edited by
              #6

              Hi All
              Thanks for your valuable responses.

              I am new to QT.
              1.)Can anyone give me code to Import & Export CSV File.
              2.)How to align different widgets on MainWindow

              Regards
              Indrajeet

              1 Reply Last reply
              0
              • L Offline
                L Offline
                loladiro
                wrote on 18 Jun 2011, 10:42 last edited by
                #7
                1. There are plenty of implementations around the internet, just use google. Otherwise you can have a look at the "specification":http://tools.ietf.org/html/rfc4180 and write one yourself for fun/practice.

                2. Use Layouts, have a look at the "documentation":http://doc.qt.nokia.com/4.7/layout.html and if you have specific questions, you can always ask (try to figure it out yourself with the documention, though)

                1 Reply Last reply
                0

                1/7

                17 Jun 2011, 09:09

                • Login

                • Login or register to search.
                1 out of 7
                • First post
                  1/7
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • Users
                • Groups
                • Search
                • Get Qt Extensions
                • Unsolved