java实现读取excel或者txt文件,导入MongoDB数据库

时间:2024-03-27 11:44:40

在工作中经常遇到读取的文件的问题,于是做了一个小总结。

1.Excel表格内容如下

java实现读取excel或者txt文件,导入MongoDB数据库

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.测试

java实现读取excel或者txt文件,导入MongoDB数据库

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的方式,请参考下一篇博文。