4 Replies Latest reply: Jan 23, 2009 2:32 AM by 807588 RSS

    Generating CSV Java.

    807588
      Hi everyone,
      I need help to generate or write to a CSV file. I am to populate the CSV with data from the database results from my ResultSet (MySql).
      Your help is most appreciated.
        • 1. Re: Generating CSV Java.
          791266
          What's the problem? Iterate over the RS and write each record to a file.

          Kaj
          • 2. Re: Generating CSV Java.
            807588
            Hi there, thank you for you quick response to my nightmare.
            I am rather stack,could you please offer some help on look at the code and offer suggestions.

            MY METHOD.

            public void generateCSV(String sFileName) throws IOException
            {
            FileWriter writer = new FileWriter(sFileName);
            String getVlaues = "SELECT name AS NAME,surname AS SURNAME,email AS EMAIL,position AS Position FROM client LIMIT 10 ";
            try
            {
            this.resultSetCreateCSV = this.connection.executeQuery(getVlaues);
            try
            {
            ResultSetMetaData rsMetaData = (ResultSetMetaData) resultSetCreateCSV.getMetaData();
            int colCount = rsMetaData.getColumnCount();
            int j=0;
            for (int i = 1; i < colCount + 1; i++) {
            String columnName = rsMetaData.getColumnName(i);
            writer.append(columnName);
            writer.append(',');
            }
            writer.append('\n');
            for(int i = 1; i < getVlaues.length() + 1; i++)
            {
            String columnValue = null;
            writer.append(getVlaues);
            writer.append(',');
            }
            }
            catch(IOException e)
            {
            e.printStackTrace();
            }
            writer.flush();
            writer.close();
            }
            catch(SQLException e) {
            e.printStackTrace( System.err );
            // this.connection.close();
            }
            }
            • 3. Re: Generating CSV Java.
              791266
              for(int i = 1; i < getVlaues.length() + 1; i++)
              {
              String columnValue = null;
              writer.append(getVlaues);
              writer.append(',');
              }
              I guess resultSetCreateCSV is a result set?

              I would in that case change to a while loop, that is something like:

              while (rs.next()) {
                //Here you want to handle each row / record by e.g. iterating over the number of columns, and write each value for a column in a row.
              }
              • 4. Re: Generating CSV Java.
                807588
                Thank you very much for you time.