Java 使用ApachePOI从Excel文件中获取列?
为了做一些统计分析,我需要在Excel表格的一列中提取值。我一直在使用ApachePOI包来读取Excel文件,当需要迭代行时,它可以正常工作。然而,无论是在API()中还是通过谷歌搜索,我都找不到任何关于获取列的信息 由于我需要获取不同列的最大值和最小值,并使用这些值生成随机数,因此,在不提取单个列的情况下,唯一的其他选择是迭代行和列以获取值并逐个比较,这听起来并不十分高效 有没有办法解决这个问题Java 使用ApachePOI从Excel文件中获取列?,java,apache,excel,apache-poi,Java,Apache,Excel,Apache Poi,为了做一些统计分析,我需要在Excel表格的一列中提取值。我一直在使用ApachePOI包来读取Excel文件,当需要迭代行时,它可以正常工作。然而,无论是在API()中还是通过谷歌搜索,我都找不到任何关于获取列的信息 由于我需要获取不同列的最大值和最小值,并使用这些值生成随机数,因此,在不提取单个列的情况下,唯一的其他选择是迭代行和列以获取值并逐个比较,这听起来并不十分高效 有没有办法解决这个问题 谢谢,Excel文件是基于行而不是基于列的,因此获取列中所有值的唯一方法是依次查看每一行。没有更
谢谢,Excel文件是基于行而不是基于列的,因此获取列中所有值的唯一方法是依次查看每一行。没有更快的方法来获取列,因为列中的单元格没有存储在一起 您的代码可能希望类似于:
List<Double> values = new ArrayList<Double>();
for(Row r : sheet) {
Cell c = r.getCell(columnNumber);
if(c != null) {
if(c.getCellType() == Cell.CELL_TYPE_NUMERIC) {
valuesadd(c.getNumericCellValue());
} else if(c.getCellType() == Cell.CELL_TYPE_FORMULA && c.getCachedFormulaResultType() == Cell.CELL_TYPE_NUMERIC) {
valuesadd(c.getNumericCellValue());
}
}
}
List values=new ArrayList();
用于(第r行:页){
单元格c=r.getCell(列号);
如果(c!=null){
if(c.getCellType()==Cell.Cell\u TYPE\u NUMERIC){
valuesadd(c.getNumericCellValue());
}else if(c.getCellType()==Cell.Cell\u TYPE\u公式和&c.getCachedFormulaResultType()==Cell.Cell\u TYPE\u数值){
valuesadd(c.getNumericCellValue());
}
}
}
这将为您提供该列中的所有数值单元格值。只是想添加,以防您的文件中有标题,并且您不确定列索引,但希望在特定标题(列名)下选择列,例如,您可以尝试类似的方法
for(Row r : datatypeSheet)
{
Iterator<Cell> headerIterator = r.cellIterator();
Cell header = null;
// table header row
if(r.getRowNum() == 0)
{
// getting specific column's index
while(headerIterator.hasNext())
{
header = headerIterator.next();
if(header.getStringCellValue().equalsIgnoreCase("column1Index"))
{
column1Index = header.getColumnIndex();
}
}
}
else
{
Cell column1Cells = r.getCell(column1);
if(column1Cells != null)
{
if(column1Cells.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
// adding to a list
column1Data.add(column1Cells.getNumericCellValue());
}
else if(column1Cells.getCellType() == Cell.CELL_TYPE_FORMULA && column1Cells.getCachedFormulaResultType() == Cell.CELL_TYPE_NUMERIC)
{
// adding to a list
column1Data.add(column1Cells.getNumericCellValue());
}
}
}
}
for(第r行:数据类型表)
{
迭代器头迭代器=r.cellIterator();
单元头=null;
//表格标题行
if(r.getRowNum()==0)
{
//获取特定列的索引
while(headerierator.hasNext())
{
header=headerIterator.next();
if(header.getStringCellValue().equalsIgnoreCase(“column1Index”))
{
column1Index=header.getColumnIndex();
}
}
}
其他的
{
Cell column1Cells=r.getCell(column1);
if(column1Cells!=null)
{
if(column1Cells.getCellType()==Cell.Cell\u TYPE\u NUMERIC)
{
//添加到列表中
column1Data.add(column1Cells.getNumericCellValue());
}
else if(column1Cells.getCellType()==Cell.Cell\u TYPE\u公式&&column1Cells.getcachedformularesultype()==Cell.Cell\u TYPE\u数值)
{
//添加到列表中
column1Data.add(column1Cells.getNumericCellValue());
}
}
}
}