使用apache poi读取excel – Hashmap,ArrayList

在这里输入图像说明

嗨,

我想在Excel中使用列标题(使用Java)读取列值。 如图所示,假设我想要读取标题“城市”,列下的所有后续单元格,并显示它们。 我将如何做到这一点?

通过互联网看的例子,我发现大部分的例子迭代使用迭代器的行。

假设我有一个key的hashmap作为excel的头文件和后来的值存储在ArrayList中。 就像是

HashMap<String, ArrayList<String>> hashmap = new HashMap<String, ArrayList<String>>(); 

我应该如何继续? 任何人都可以帮助我的代码和逻辑?

请不要将其标记为重复,我已经尝试过在stackoverflow和internet上search,但是其中大多数使用该行进行迭代。

没有办法直接读取列中的所有单元格而无需迭代行,因为数据存储在Excel工作表(行,而不是列)中的方式。 解决方法可以是像这里显示的那样对行和列进行转置,然后遍历行来获取数据,如同在问题中指出的那样。

首先,你将读取第一行后,你可以得到所有的列值,下面我已经给出了如何读取第一行

 public void readFirstRow(String filename) { List<String> fieldsArrayList = new ArrayList<String>(); try{ FileInputStream myInput = new FileInputStream(new File(filename)); Workbook workBook = null; workBook = new HSSFWorkbook(myInput); Sheet sheet = workBook.getSheetAt(0); Row firstRow = sheet.getRow(0); int length = firstRow.getLastCellNum(); Cell cell = null; for( int i = 0 ; i < length ; i++ ) { cell = firstRow.getCell(i); fieldsArrayList.add(cell.toString()); } } catch(Exception e) { e.printStackTrace(); } } 

读取列值代码:

//你只需传递cityPostion和文件名

 public void readColumnValues(int cityPosition,String fileName) { try { FileInputStream myInput = new FileInputStream(fileName); Workbook workBook = null; workBook = new HSSFWorkbook(myInput); Sheet sheet = workBook.getSheetAt(0); for ( int i = 0 ; i <= sheet.getLastRowNum() ; i++ ) { Row row = sheet.getRow(i); if (i > 0) //skip first row { Cell cityCell = row.getCell(cityPosition); String cityNames = cityCell.toString(); } } } catch(Exception e) { e.printStackTrace(); } } 

可能会对你有帮助…