Convert Resultset to CSV file using Java

前提是你 提交于 2020-05-08 05:33:10

问题


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++;   
            }  

回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/18128802/convert-resultset-to-csv-file-using-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!