0

As the title states, I'm exporting a java query from a local database into a CSV file, all the required information prints out correctly, however my column headers Print out in Column A (row 1-8) and not along columns (A-H). in short i have headers 1-8 printing in column 1, followed by thousands of rows of data in the correct order. Pretty new to java, sorry if I'm being silly!

        PrintWriter out = new PrintWriter(new BufferedWriter(
                new FileWriter("TestingRawData.csv")));

        ResultSetMetaData rsmd = result.getMetaData();
        int columnCount = rsmd.getColumnCount();

        for (int i = 1; i < columnCount + 1; i++) {
            String name = rsmd.getColumnName(i);
            out.println(name);
            // print the name
        }

        while (result.next()) {
            out.println(String.format("%s,%s,%s,%s,%s,%s,%s,%s",
                    result.getString(1), result.getString(2),
                    result.getString(3), result.getString(4),
                    result.getString(5), result.getString(6),
                    result.getString(7), result.getString(8)));

        }
2
  • Not related to your question, but each datafield should be surrounded by double quotes. That prevents any problems caused by commas in your data. Commented Feb 10, 2014 at 16:25
  • Thank you, will sort it just now Commented Feb 10, 2014 at 16:28

1 Answer 1

0

Apart from the fact that this should be done using a CSV library such as OpenCSV, println outputs a newline. Use print instead

for (int i = 1; i < columnCount + 1; i++) {
    String name = rsmd.getColumnName(i);
    out.print(name);
    if (i != columnCount + 1) {
      out.print(",");
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the reply =), now it prints my 8 table headers one after another in Column A row 1
You'll need to output the separators yourself - that's why using a CSV library is soo much better :)
Thanks man! works now, all headers are showing, i will have a look at the CSV library, i was reading about that somewhere so i will change it, do you have any idea why now Columns I-P contain data? just one row, showing up as headers (when they should be blank) thank you again
As well as OpenCSV, also look at JacksonCSV mapper for a CSV library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.