1、导入依赖包
mongodb-driver-3.4.2.jar
mongodb-driver-core-3.4.2.jar
bson-3.4.2.jar
poi-3.10.1-20140818.jar
2、直接上代码
public class ExcelToMongo {
private static Integer PORT = 27017; //端口号
private static String IP = "localhost"; //Ip
private static String DATABASE = "database"; //数据库名称
private static String USERNAME = "username"; //用户名
private static String PASSWORD = "password"; //密码
private static String COLLECTION = "test"; //文档名称
private static String ADDRESS = "xxx.xls"; //Excel文件所在的路径
public static void main(String[] args) {
try {
// 输入文件
FileInputStream inputStream = new FileInputStream(ADDRESS);
// 根据输入流导入Excel产生Workbook对象
Workbook workbook = null;
try {
workbook = new HSSFWorkbook(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
// IP,端口
ServerAddress serverAddress = new ServerAddress(IP, PORT);
List<ServerAddress> address = new ArrayList<ServerAddress>();
address.add(serverAddress);
// 用户名,数据库,密码
MongoCredential credential = MongoCredential.createCredential(USERNAME, DATABASE, PASSWORD.toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
// 通过验证获取连接
MongoClient mongoClient = new MongoClient(address, credentials);
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase(DATABASE);
// 连接文档
MongoCollection<Document> collection = mongoDatabase.getCollection(COLLECTION);
System.out.println("连接成功");
List<Document> documents = new ArrayList<Document>();
List<String> fieldList = new ArrayList<String>();
// 获取Excel文档中第一个表单
Sheet sheet = workbook.getSheetAt(0);
Row row0 = sheet.getRow(0);
for (Cell cell : row0) {
fieldList.add(cell.toString());
}
int rows = sheet.getLastRowNum() + 1;
int cells = fieldList.size();
for (int i = 1; i < rows; i++) {
Row row = sheet.getRow(i);
Document document = new Document();
for (int j = 0; j < cells; j++) {
Cell cell = row.getCell(j);
document.append(fieldList.get(j), cell.toString());
}
documents.add(document);
}
collection.insertMany(documents);
System.out.println("插入成功");
} catch (FileNotFoundException e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
}