java - 如何首先在Excelsheet上写入最后插入的数据?

标签 java mongodb

我正在使用 apache poi 在 excelsheet 上写入 mongodb 数据,但它在 excel 的第一行写入了第一个插入的数据,但我需要在第一行上最后插入的数据我想在 excelsheet 上打印最后到第一个有人可以帮助我吗如何做到这一点,这是我的代码。

public static void main(String args[]) throws IOException {
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Sheet1");
    //HSSFSheet sheet = wb.createSheet("Excel Sheet");
    XSSFRow rowhead;
    rowhead = sheet.createRow(0);
    rowhead.createCell(0).setCellValue("Employee ID");
    rowhead.createCell(1).setCellValue("Name");
    rowhead.createCell(2).setCellValue("Phone Number");
    rowhead.createCell(3).setCellValue("Domain");
    rowhead.createCell(4).setCellValue("Address");


    try {

        // To connect to mongodb server
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // Now connect to your databases
        DB db = mongoClient.getDB("test");
        System.out.println("Connect to database successfully");

        DBCollection collection = db.getCollection("testCollection");
        System.out.println("Collection mycol selected successfully");

        DBCursor cursor = collection.find();
        int i = 1;
        while (cursor.hasNext()) {
            DBObject o = cursor.next();
            //String fname = (String) o.get("Employee ID") ; 
            String lname = (String) o.get("Name");
            String sid = (String) o.get("Phone Number");
            String prg = (String) o.get("Domain");
            String lvl = (String) o.get("Address");

            Row row = sheet.createRow(i);
            row.createCell(0).setCellValue(lname);
            row.createCell(1).setCellValue(sid);
            row.createCell(2).setCellValue(prg);
            row.createCell(3).setCellValue(lvl);
            i++;

        }
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }

    try (FileOutputStream outputStream = new FileOutputStream("datasheet.xlsx")) {
        workbook.write(outputStream);
    }

}

最佳答案

对于后进先出 cursor.sort(new BasicDBObject("_id", -1));

关于java - 如何首先在Excelsheet上写入最后插入的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42801884/

相关文章:

java - 打印二叉树的层序遍历,从左到右和从右到左交替

java - 已 sleep 线程上的 Sleep() 方法

Java 驱动程序 : how to get the objectId of an updated object with Mongodb's updateFirst method

java - MongoDB - 在内存中保存 DBCursor 时对数据库进行更改

java - 使用 Java 中的 Calendar 类进行日期操作

java - 有什么方法可以找出(在运行时)哪个实体导致了 ConstraintViolationException?

java - 使用 Reactor 抛出异常的正确方法

ruby connect.rb 连接到 Mongo 但 irb -r connect.rb 失败

mongodb - 如何通过管道函数获取子字段值

node.js - Mongoose 不插入数据