在Excel表格的一列中计算行数(提供Java代码)

3
关于我之前的问题如何使用Java计算Excel文档中一列中的行数,我已经能够计算出给定表格中的总列数。现在还有一半的工作需要完成,因为我想要计算特定列中的行数。可能的解决方案是使用2D数组并存储列索引和总行数,或者使用map等。我该如何实现呢?这里提供了Java代码。我对我的演示文件获取了正确的计数(列计数)。请根据需要修改/建议更改。

(编辑):我已经使用哈希映射来计算存储列索引作为键和行计数作为值,但它没有起作用,可能应用的逻辑是错误的。好吧,如果我想使用哈希映射完成这个任务,在迭代时我该如何将特定列中的行数存储为

Java代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

import org.apache.poi.ss.formula.functions.Column;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelRead {
    static int colrange=1000;
    public static void main(String[] args) {
        HashMap hm=new HashMap();
        int count=0;
    try {
        FileInputStream file = new FileInputStream(new File("C:/Users/vinayakp/Desktop/Demo2.xlsx"));
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();
        while(rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            while(cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                switch(cell.getCellType()) {
                    case Cell.CELL_TYPE_BOOLEAN:
                        System.out.print(cell.getBooleanCellValue() + "\t\t");
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t\t");
                        break;
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "\t\t");
                        break;
                }
            }
            System.out.println("");
        }

        for(Row r:sheet)
        {
            short minColIx=r.getFirstCellNum();
            short maxColIx=r.getLastCellNum();
            for(short colIx=minColIx;colIx<maxColIx;colIx++) {
                Cell c= r.getCell(colIx);
                if(c!=null) {
                    if(c.getCellType()== Cell.CELL_TYPE_STRING||c.getCellType() == Cell.CELL_TYPE_NUMERIC||c.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
                        count++; ---// can i use hashcode in here to get the key and value pair? key=column index value=total number of rows in that column
                            } 
                    }
                    else break;
                }
            }

        System.out.println("\nTotal Number of columns are:\t"+count);
        System.out.println(hm);
        file.close();    
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException ae) {
        ae.printStackTrace();
    }
}
}
3个回答

7

试试这个:

private void excelReader() {
    String data;
    try {
        InputStream is = new FileInputStream("Read.xlsx");
        Workbook wb = WorkbookFactory.create(is);
        Sheet sheet = wb.getSheetAt(0);
        Iterator rowIter = sheet.rowIterator();
        Row r = (Row)rowIter.next();
        short lastCellNum = r.getLastCellNum();
        int[] dataCount = new int[lastCellNum];
        int col = 0;
        rowIter = sheet.rowIterator();
        while(rowIter.hasNext()) {
            Iterator cellIter = ((Row)rowIter.next()).cellIterator();
            while(cellIter.hasNext()) {
                Cell cell = (Cell)cellIter.next();
                col = cell.getColumnIndex();
                dataCount[col] += 1;
                DataFormatter df = new DataFormatter();
                data = df.formatCellValue(cell);
                System.out.println("Data: " + data);
            }
        }
        is.close();
        for(int x = 0; x < dataCount.length; x++) {
            System.out.println("col " + x + ": " + dataCount[x]);
        }
    }
    catch(Exception e) {
        e.printStackTrace();
        return;
    }
}

测试代码

我创建了一个包含以下单元格数据的xlsx文件:

Col0    Col1    Col2    Col3    Col4
1       a       x       a       q
2       b       y       s       w
3       c       z       d       e
4       d               f       r
5       e                       t
                                y

数据计数数组的内容如下:
第0列:6
第1列:6
第2列:4
第3列:5
第4列:7
右侧的数字表示每列数据单元格的数量,包括标题行。
如果要排除标题行,只需在while循环之前删除以下代码行:
rowIter = sheet.rowIterator();
这符合您的要求吗?

我已经完成了这个任务...对于一个列,它给出了正确的答案...现在我用for循环来尝试整个工作表,但是没有得到期望的结果。你能否编辑答案并告诉我如何遍历具有10个列的工作表列表? - Vinayak Pahalwan
我已经修改了代码,请检查它是否能正常工作,因为我还没有测试过。=) - TheQuickBrownFox
输出为:数据:A 数据:B 数据:C……等等(打印标题和单元格内容) - Vinayak Pahalwan
问题在于它按行读取数据,而我所做的是能够提取1个单元格并计算数据行数,但当我迭代时,它给出了错误的结果。那么我是否需要逐个单元格计算数据? - Vinayak Pahalwan
据我所知,您需要逐个单元格、逐行执行此操作。我现在不在电脑旁无法编写代码,因此无法确认。 - TheQuickBrownFox
显示剩余4条评论

1

这会解决问题吗?

HSSFSheet mySheet = myWorkBook.getSheetAt(0);
                Iterator<Row> rowIter = mySheet.rowIterator();
                while (rowIter.hasNext()) {
                    HSSFRow myRow = (HSSFRow) rowIter.next();
                    Iterator<Cell> cellIter = myRow.cellIterator();
                    List<HSSFCell> cellStore = new ArrayList<HSSFCell>();
                    while (cellIter.hasNext()) {
                        HSSFCell myCell = (HSSFCell) cellIter.next();
                        rowCount++ //For myRow
                    }

                }

它正在给出Excel表格中的数据总数,包括标题列名称。 我想要的是计算特定列中数据的数量,例如_ColumnA有5行_。 - Vinayak Pahalwan

0
它正在提供Excel表中的数据总数,我的意思是包括标题列名称。

在我看来,您想要计算一列中有多少行,但不包括标题行。
如果是这样,您可以使用Binu提供的解决方案。只需修改它以跳过列名所在的行即可。

除了标题行以外的所有程序相关内容。是的,我需要那个...我正要尝试那个。 - Vinayak Pahalwan
你只是对计算行数感兴趣吗?还是也想存储数据? - TheQuickBrownFox
只需计算特定列的行数,例如... 列A有5条数据 ,这必须是输出结果,其他列也同样如此。 - Vinayak Pahalwan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接