Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Resultset to CSV file using Java

Hi I am trying to convert oracle jdbc resultset to csv file. Below is the code used. Issue occures when there is value like below in the field. It deforms the output csv and all this come in separate line rather than in one field.

Value in Field comes in csv as

[<333message:Runtime error in script' ProcessItem: ' Type: 'ITEM'" 1:0).Internal Script error: java.lang.NullPointerException
Script (line 1):
setHours = 0 ;
if(ts.instanceId == null)
" 3 : ts.instanceId = 0 ;"
Step >]

int ncols = result.getMetaData().getColumnCount();  

            System.out.println("ColumnCout"+ncols);  
            FileOutputStream fos=new FileOutputStream(new File("C:\\test.csv"),false);  
            Writer out = new OutputStreamWriter(new BufferedOutputStream(fos),"UTF_8");      

            for (int j=1; j<(ncols+1); j++) {     
            out.append(result.getMetaData().getColumnName (j));       
            if (j<ncols) out.append(","); else out.append("\r\n");      
            }   
            int m =1;    

            while (result.next()) {   

            for (int k=1; k<(ncols+1); k++) {   

            out.append(result.getString(k));    

            if (k<ncols) out.append(","); else out.append("\r\n");    
            }   
            //System.out.println("No of rows"+m);   
            m++;   
            }  
like image 932
Devesh Avatar asked Aug 08 '13 14:08

Devesh


People also ask

How to write the data into CSV file using Java?

Writing a CSV file is as simple as reading. Create an instance of CSVWriter by passing FileWriter object as parameter and start writing data to CSV file using methods of CSVWriter Class. After writing data we need to close CSVWriter connection by calling close() method of CSVWriter class.

What is csv file in Java?

A Comma-Separated Values (CSV) file is just a normal plain-text file, store data in column by column, and split it by a separator (e.g normally it is a comma “, ”). OpenCSV is a CSV parser library for Java.


2 Answers

Are you using "java.sql.ResultSet" class? If yes, see the library in this link http://opencsv.sourceforge.net/

See an example:

CSVWriter csvWriter = new CSVWriter(new FileWriter("yourfile.csv"), '\t');
java.sql.ResultSet myResultSet = .... ;
csvWriter.writeAll(myResultSet, includeHeaders);
like image 63
Jacobi Avatar answered Sep 30 '22 10:09

Jacobi


Get the value for the column that could have new lines as

String multiLine = null;
if (k == <col_index> && (mutiLine = rs.getString(k)) != null)
    out.append(multiLine.replaceAll("\\n", ""));
else
    out.append(result.getString(k));

You could filter all the columns as well but then would incur some performance hit.

like image 28
Ravi K Thapliyal Avatar answered Sep 30 '22 09:09

Ravi K Thapliyal