用单个键和多个值将地图写入Excel工作表

我有一个单一的键和多个值的Map我试图把这些数据写入Excel表格。

 Map<String, Object[]> data=new TreeMap<String, Object[]>(); 

在这张地图上,我正在提出一些价值观。

 ContentRoleType role=ContentRoleType.toContentRoleType("PRIMARY"); QueryResult contentQuery=ContentHelper.service.getContentsByRole(cadDoc, role); System.out.println("Content length of "+cadDoc.getName()+" is "+contentQuery.size()); ContentLength=contentQuery.size(); data.put(CadName, new Object[]{Iteration,ContentLength}); 

然后我遍历这个映射并将这些元素写入单元格。

 Set<String> keyset=data.keySet(); int rowNum=0; for(String key:keyset){ Row row=sheet.createRow(rowNum++); Object[] objArr=data.get(key); int cellNum=0; for(Object obj:objArr){ Cell cell=row.createCell(cellNum++); if(obj instanceof String) cell.setCellValue((String)obj); else if(obj instanceof Integer) cell.setCellValue((Integer)obj); } } try { //Write the workbook in file system FileOutputStream out = new FileOutputStream(new File("D:\\testExcel.xlsx")); workbook.write(out); out.close(); System.out.println("testExcel.xlsx written successfully on disk."); } catch (Exception e) { e.printStackTrace(); } 

这里的问题是在我的Excel表中,我只能看到两列是值。我不能打印在Excel表内的键。我想打印我的关键作为我的第一列,然后两个和三个值。如何添加这个循环内的关键?

感谢所有

你不会在内部循环中添加键 – 它不是你正在循环的数据的一部分。 你需要在循环之前添加它:

 row.createCell(0).setCellValue(key); // Key is in column 0 int cellNum = 1; // Values now start at column 1 // Loop as before 

(当然,这仍然在外部循环中 – 你想要显示每行一个键。)