我想使用excel的列标题作为键,以便我可以使用该键明确打印特定数据。下面是我使用row作为键的代码,但不能按列顺序执行:
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheet("Bill");
Iterator<Row> rowIterator = sheet.iterator();
HashMap<Integer,List<String>> m= new HashMap<>();
int rownum=0;
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<String> lst=new LinkedList<String>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
int a=(int) cell.getNumericCellValue();
lst.add(Integer.toString(a));
break;
case Cell.CELL_TYPE_STRING:
lst.add(cell.getStringCellValue());
break;
}
}
m.put(rownum,lst);
rownum++;
}
for (int i:m.keySet())
{
System.out.println(i+"-----"+m.get(i));
}
答案 0 :(得分:0)
阅读下面的excel代码。在读取excel后,使用键“columns”将第一列放入地图中,使用
获取列列表列列=(列表)dataList.get(0).get(“columns”);
public List<HashMap<String, Object>> readExcel(InputStream inputStream, String dateFormat) {
ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
try {
XSSFWorkbook workbook;
workbook = new XSSFWorkbook(inputStream);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = spreadsheet.iterator();
int c = 0;
ArrayList<String> columns = new ArrayList<String>();
while (rowIterator.hasNext()) {
row = (XSSFRow) rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
HashMap<String, Object> map = new HashMap<String, Object>();
if (c == 0) {
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell.getStringCellValue().trim() != null && !cell.getStringCellValue().trim().equals("")) {
columns.add(cell.getStringCellValue().trim());
}
}
} else {
for (int i = 0; i < columns.size(); i++) {
Cell cell = row.getCell(i);
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellInternalDateFormatted(cell)) {
DateFormat df = new SimpleDateFormat(dateFormat);
map.put(columns.get(i), df.format(cell.getDateCellValue()));
break;
} else {
map.put(columns.get(i), cell.getNumericCellValue());
break;
}
case Cell.CELL_TYPE_STRING:
map.put(columns.get(i), cell.getStringCellValue().trim());
break;
}
} else {
map.put(columns.get(i), "");
}
}
}
if (c == 0) {
map.put("columns", columns);
}
c++;
if (!isEmptyRow(map)) {
map.put("rowNumber", c);
result.add(map);
}
}
inputStream.close();
return result;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}