我正在尝试使用POI和hashMaps编写Excel工作表。我的代码成功创建并填充了Excel工作表,但并未将所有信息写入工作表。在调试模式下,它似乎写入5个键值对,然后循环到键[0]的开头。有人可以告诉我我的逻辑中的错误在哪里吗?
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(make + " sheet");
int rowNum = 0;
ConcurrentHashMap <Integer, String[] > data = new
ConcurrentHashMap<Integer, String[]>();
data.put(rowNum++, new String[] {"VIN", "Make", "Model", "Year",
"Major Group", "Caption", "Cap Filter", "Illustration",
"Illus Filter", "PNC", "Part Name", "Part Number", "Quantity",
"Part Filter"});
for (Part p : plist){
String PNC = p.getPNC();
String quantity = p.getQuantity();
if(vFilterId.contains(p.getId())) {
data.put(rowNum++ , new String[] {vinId, make,
model, year, group, caption, capFilter, illusName,
iFilter, PNC, p.getName(), p.getPartNumber(),
quantity, "NONFILTERED"});
} else {
data.put(rowNum++ , new String[] {vinId, make,
model, year, group, caption, capFilter, illusName,
iFilter, PNC, p.getName(), p.getPartNumber(),
quantity, "NONFILTERED"});
}
}
int rowIndex = 0;
Set<Integer> keyset = data.keySet();
for (Integer key : keyset) {
Row row = sheet.createRow(rowIndex++);
Object[] objArr = data.get(key);
int cellIndex = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellIndex++);
cell.setCellValue((String) obj);
}
}
try {
FileOutputStream fos = new FileOutputStream(outputFile);
workbook.write(fos);
fos.close();
System.out.println("XLS sheet written.");
} catch (IOException e) {
e.printStackTrace();
}
}
return ReturnConstants.SUCCESS;
}
提前致谢!
答案 0 :(得分:0)
您正在使用地图存储表示表中行的数据。您最好使用List,因为地图通常没有排序(即条目的顺序可能随时间而变化)。
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(make + " sheet");
List<String[]> data = new ArrayList<String[]>();
data.add(new String[] {"VIN", "Make", "Model", "Year",
"Major Group", "Caption", "Cap Filter", "Illustration",
"Illus Filter", "PNC", "Part Name", "Part Number", "Quantity",
"Part Filter"});
for (Part p : plist){
String PNC = p.getPNC();
String quantity = p.getQuantity();
if(vFilterId.contains(p.getId())) {
data.add(new String[] {vinId, make,
model, year, group, caption, capFilter, illusName,
iFilter, PNC, p.getName(), p.getPartNumber(),
quantity, "NONFILTERED"});
} else {
data.add(new String[] {vinId, make,
model, year, group, caption, capFilter, illusName,
iFilter, PNC, p.getName(), p.getPartNumber(),
quantity, "NONFILTERED"});
}
}
for (int rowIndex=0; rowIndex<data.size(); rowIndex++) {
Row row = sheet.createRow(rowIndex);
Object[] objArr = data.get(rowIndex);
int cellIndex = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellIndex++);
cell.setCellValue((String) obj);
}
}
答案 1 :(得分:0)
如果不调试代码很难确定,但根据您的描述,您的密钥集变量似乎只包含3个条目,这就是您只输出3行的原因。所以我要做的第一件事就是显示(使用System.out.println)data.size()和keyset.size()来查看它们有多大。我猜测其中一个或两个只有3号。
您是否展示了所有相关代码?我想也许不是,因为,例如,无论是否执行if code或else子句,if语句似乎都是多余的,因为你输出相同的东西。
我同意第一个答案,即不需要使用HashMap;一个ArrayList也可以正常工作。但是,正如您所发现的,这与您为何只看到3行无关。
抱歉,我不能提供更多帮助,但我认为使用System.out.println进行一些调试将有助于发现问题所在。