java實現讀取excel或者txt檔案,匯入MongoDB資料庫
阿新 • • 發佈:2018-12-08
在工作中經常遇到讀取的檔案的問題,於是做了一個小總結。
1.Excel表格內容如下
2.建立main主類
public static void main(String[] args) throws Exception {
ReadExcel read = new ReadExcel();
File file = new File("D:/test/c.xls");
read.readExcel(file);
}
3.建立工具類ReadExcel
public void readExcel(File file) throws Exception {// 建立檔案輸入流物件
InputStream is = new FileInputStream(file.getAbsolutePath());
Workbook wb = Workbook.getWorkbook(is);
int sheet_size = wb.getNumberOfSheets();
// 建立MongoDB物件,連線資料來源
MongoClient mongo = new MongoClient("localhost", 27017);
// 要插入的資料庫
MongoDatabase db = mongo.getDatabase("one");
// 要插入的集合,如果沒有就自動建立一個集合demo
MongoCollection<Document> coll = db.getCollection("demo");
for (int index = 0; index < sheet_size; index++) {
Sheet sheet = wb.getSheet(0);
// 表格的頭
List<String> head = new ArrayList<>();
head.add("CompanyName");
head.add("userAmount");
head.add("raking");
head.add("FatherName");
head.add("date");
head.add("user");
head.add("number");
List<Document> docs = new ArrayList<Document>();
// 表個的所有行
int rows = sheet.getRows();
// 表個的所有列
int columns = sheet.getColumns();
for (int i = 1; i < rows; i++) {
List<Object> list = new ArrayList<>();
Document document = new Document();
for (int j = 0; j < columns; j++) {
// 獲取每個單元的內容,預設都是string
String cellinfo = sheet.getCell(j, i).getContents();
if (j == 1 || j == 2) {
if (StringUtils.isNotBlank(cellinfo)) {
Integer num = Integer.valueOf(cellinfo);
list.add(num);
} else {
list.add(null);
}
} else if (j == 4) {
// 存入date格式內容
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date date = format.parse(cellinfo);
list.add(date);
} else if (j == 5) {
// 存入物件的格式內容
// name:lxj/age:24 - name:tom/age:22
List<Map<String, Object>> li = new ArrayList<>();
String[] split = cellinfo.split(" - ");
for (String string : split) {
Map<String, Object> map = new HashMap<>();
String[] split2 = string.split("/");
map.put("name", split2[0].split(":")[1]);
map.put("age", Integer.valueOf(split2[1].split(":")[1]));
li.add(map);
}
list.add(li);
} else if (j == 6) {
// MongoDB不支援存陣列,需要將陣列轉換為List物件
String[] split = cellinfo.split(",");
list.add(Arrays.asList(split));
} else {
list.add(cellinfo);
}
System.out.println(cellinfo);
}
// 插入到Mongo中
for (int m = 0; m < head.size(); m++) {
document.put(head.get(m), list.get(m));
}
docs.add(document);
}
coll.insertMany(docs);
}
}
4.測試
5.總結,這樣檔案就從excel成功匯入到了MongoDB中
注1:
如果直接存入陣列,會報如下的錯誤:
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class [Ljava.lang.String;.
注2:
如果檔案是txt格式,並且資料時有格式的,可以直接改字尾名,用excel開啟,讀取檔案。有的檔案是csv格式的,不過有的可能是版本的原因,不支援。這個時候,讓檔案另存為Excel 97-2003 xls格式,就可以了呢。
注3:
如果檔案過大,超過excel的65535範圍,可使用讀取txt的方式,請參考下一篇博文。