java导出数据写入csv代码

java | 2019-09-13 10:02:39

java导出csv工具代码:

package com.du.string;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.Properties;
public class Pro2 {
    public void run(){
        try{
             
             
            Properties prot =new Properties();
            InputStream fis=new FileInputStream(new File("./config.properties"));
            prot.load(fis);
            System.out.println(prot.getProperty("tables"));
            System.out.println(prot.getProperty("csvpath"));
             
            RandomAccessFile raf=new RandomAccessFile(prot.getProperty("csvpath"), "rw");
            raf.seek(raf.length());
             
            Class.forName(prot.getProperty("driver"));
            Connection conn=DriverManager.getConnection(prot.getProperty("jdbc"),prot.getProperty("user"),prot.getProperty("password"));            
            Statement st=conn.createStatement();
            ResultSet rs;
            String table=prot.getProperty("tables");
            int limit,count;
             
            limit=Integer.parseInt(prot.getProperty("limit"));
            rs=st.executeQuery("select count(1) from "+table);  
            rs.next();
            count=rs.getInt(1)/limit+1;
             
            System.out.println(count);
             
            for(int k=0;k<=count;k++){
            rs=null;
            rs= st.executeQuery("select * from "+table+" limit "+limit+" offset "+k*limit);
            ResultSetMetaData rsmd=rs.getMetaData();
             
            if(k==0){
            String columnC="";
            for(int i=1;i<=rsmd.getColumnCount();i++){
                columnC=columnC+rsmd.getColumnName(i).toString();
                if(i<rsmd.getColumnCount()){
                    columnC=columnC+",";
                }
            }
            raf.write(columnC.getBytes());
            }
             
            while (rs.next()){
                String ls="";
                for(int i=1;i<=rsmd.getColumnCount();i++){
                    ls=ls+rs.getObject(i).toString();
                     
                    if(i<rsmd.getColumnCount()){
                        ls=ls+",";
                    }
                }
                raf.write("\r\n".getBytes());
                raf.write(ls.getBytes());
            }
            raf.write(("\r\nPage+"+k).getBytes());
            }
            raf.close();
            conn.close();
             
        }
        catch(Exception e){
            e.printStackTrace();
        }
        finally{
        }
    }
    public static void main(String[] args) {
        Pro2 p=new Pro2();
        p.run();
    }
     
}


登录后即可回复 登录 | 注册
    
关注编程学问公众号