远程从Mongodb 数据库中导出为CSV文件

Java 连接Mongodb 数据库并且从数据库导出数据为CSV文件。

需要导入三个包:

bson-3.4.3.jar

mongo-java-driver-3.4.3.jar

mongodb-driver-core-3.4.3.jar


当然版本可以改变。可以从http://mongodb.github.io/mongo-java-driver/ 这里下载

mongodb.properties:

url=localhost
port=27017

连接数据库的工具类:

package com.qitech.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.Properties;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class MongoDbConn {
	private static String url;
    private static int port;

    // 初始化加载
    static{
        //加载
        Properties p = new Properties();
        InputStream input = MongoDbConn.class.getClassLoader().getResourceAsStream("mongodb.properties");
        try {
            p.load(input);
            url = p.getProperty("url");
            port = Integer.valueOf(p.getProperty("port"));
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 获取连接mongodb
     * @Description:
     * @param @return 
     * @return DBCollection 返回类型
     */
    public static DBCollection getConn(String db,String table) throws UnknownHostException{
        DBCollection conn = null;
        try {
            @SuppressWarnings("deprecation")
			Mongo m = new Mongo(url,port);
            DB d = m.getDB(db);
            conn = d.getCollection(table);
        } catch (MongoException e) {
            e.printStackTrace();
        }
        return conn;
    }
    /**
     * 关闭连接
     * @Description:
     * @param @param m 
     * @return void 返回类型
     */
    public static void getClose(Mongo m){
        m.close();
    }
}



导出CSV 文件的工具类:

package com.qitech.util;

import java.io.IOException;
import java.util.ArrayList;
import com.csvreader.CsvWriter;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

public class WriteCsvUtil {
	public static void Csv(DBCursor cursor,String fileName) throws IOException{
		 CsvWriter csvWriter = new CsvWriter(("F:/"+fileName));
		//获取标题
		 
		 DBObject ob = cursor.toArray().get(0);
		 
		 ArrayList<String> title = new ArrayList<String>();
		 for(String key:ob.keySet()){
	            title.add(key);
	        }
		 
		 String[] buffer = new String[100];
		 String[] buffer1 = new String[10000];
		 
		for(int i = 0;i< (cursor.count() + 1);i++){
			int k=0;
			//创建标题行
			if(i == 0){
				for(int j=0;j<title.size();j++){
					buffer[k] = title.get(j);
					k++;
				}
				continue;
			}
		
			if(i == 1){
				csvWriter.writeRecord(buffer);
			}
		

			//写数据
			DBObject obj = null;
			for(int j = 0;j < title.size();j++){
				int k1=0;
				obj = cursor.toArray().get(i-1);
				for(String key : obj.keySet()){				
	                if (key.equals(title.get(j))) {
	                    buffer1[k1] = obj.get(key).toString();
	                }
	                k1++;
				}
				
			}
		csvWriter.writeRecord(buffer1);
		}
		try {
			
			System.out.println("aaa");
			
		} catch (RuntimeException r) {
			// TODO Auto-generated catch block
			new RuntimeException("导出CSV 文件出错");
		}finally {
			System.out.println("导出文件成功");
			//csvWriter.flush();
			csvWriter.close();
		}
	}
}
	


测试类:


public static void main(String[] args) throws IOException {
		DBCollection conn = null; 
		try {
			conn = MongoDbConn.getConn("local", "student");
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		DBCursor cursor = conn.find();
		
		
		WriteCsvUtil.Csv(cursor, "1.csv");
	}

导出截图:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值