我正在构建一个程序,使用Apache POI将信息打印到.xlsx文件中,它看起来效果很好,但是由于我在打印输出过程中添加了更多行,因此出现了打嗝。我使用带有整数键和字符串对象数组的HashMap来存储信息,然后写入excel文件。一切都很好,直到与键17一致。程序开始混淆行并按顺序打印它们。这是代码,下面是它打印出来的方式。注意第17和18行如何混合以及如何省略2个空行。我错过了什么可能导致这种疯狂?谢谢大家!
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Estimate");
//Create a new row in current sheet
Row row = sheet.createRow(0);
//Create a new cell in current row
Cell cell = row.createCell(0);
//Set value to new value
cell.setCellValue("");
Map<Integer, Object[]>
data = new HashMap<Integer, Object[]>();
data.put(0, new Object[] {"", "SIZE 1 (in inches)", "SIZE 2 (in inches)", "PRICE"});
data.put(1, new Object[] {"P-BOARD:" });
data.put(2, new Object[] {""});
data.put(3, new Object[] {"","AMOUNT PER SQFT", "COUNT", "PRICE"});
data.put(4, new Object[] {"SCREWS:"});
data.put(5, new Object[] {""});
data.put(6, new Object[] {"", "PRICE 50 lb BAG", "PRICE 25 lb BAG"});
data.put(7, new Object[] {"MORTAR:"});
data.put(8, new Object[] {""});
data.put(9, new Object[] {"", "PRICE"});
data.put(10, new Object[] {"TROWEL"});
data.put(11, new Object[] {""});
data.put(12, new Object[] {"", "PRICE"});
data.put(13, new Object[] {"GROUT FLOAT"});
data.put(14, new Object[] {""});
data.put(15, new Object[] {"", "PRICE"});
data.put(16, new Object[] {"LARGE BUCKET"});
data.put(17, new Object[] {""});
data.put(18, new Object[] {""});
data.put(19, new Object[] {"TILE DIMENSION 1", "TILE DIMENSION 2", "BRAND", "PRICE"});
Set<Integer> keyset = data.keySet();
int rownum = 0;
for (Integer key : keyset)
{
Row row1 = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
Cell cell1 = row1.createCell(cellnum++);
if(obj instanceof Date)
cell1.setCellValue((Date)obj);
else
if(obj instanceof Boolean)
cell1.setCellValue((Boolean)obj);
else
if(obj instanceof String)
cell1.setCellValue((String)obj);
else
if(obj instanceof Double)
cell1.setCellValue((Double)obj);
}
}
答案 0 :(得分:4)
java HashMap没有固有的顺序。有关更长的答案,请参阅here。 你为什么首先使用Map而不仅仅是List?
如果要继续使用HashMap。在迭代之前订购你的keySet。
以下是如何获取整数键的排序列表:
List<Integer> keys = new ArrayList<>( data.keySet() );
Collections.sort( keys );