我正在使用 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/