计算Excel表格一列中的行数(提供Java代码) [英] Count number of rows in a column of Excel sheet(Java code provided)

查看:43
本文介绍了计算Excel表格一列中的行数(提供Java代码)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考我之前的问题 如何使用 Java 计算 Excel 文档列中的行数 我能够计算给定工作表中的总列数.现在还有一半的工作尚未完成因为我想计算特定列中的行数.可能的解决方案可能是使用二维数组并存储列索引和总行数或使用地图等.我如何实现这一点?此处提供了 Java 代码.我的演示文件得到了正确的计数(列数).请根据需要修改/建议更改.

In reference to my previous question How to calculate number of rows in a column of Excel document using Java i was able to calculate the total number of columns in the given sheet. Now half of the work is yet to be done as i want to calculate the number of rows in a particular column. Possible solution could be using 2d array and storing column index and the total rows or using map, etc. How i can achieve this? Java code is provided here. I'm getting right count(column count) for my demo file. Please modify/suggest changes as required.

(编辑):我使用hasp map 计算存储列索引作为键和行计数作为值,但它不起作用,可能是应用的逻辑是错误的.好吧,如果我想通过使用 Hash Map 来实现这一点,如何将特定列中的行数(迭代时) 存储为 值em>

(edit): i've used hasp map to calculate store column index as key and row count as value, but it wasnt working, may be the applied logic was wrong. Well, if i want to accomplish this by using Hash Map, how i can store number of rows in a particular column(while iterating) as a value

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();
    }
}
}

推荐答案

试试这个:

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 文件:

Tested code

I created an xlsx file with the following cell data:

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

dataCount数组的内容是这样的:

The contents of dataCount array is this:

第 0 列:6

第 1 列:6

第 2 列:4

第 3 列:5

第 4 列:7

右边的数字计算每列包含数据的单元格数量,包括标题行.

The numbers on the right count the number of cells with data for each column, including the header row.

如果要排除标题行,只需删除该行:

If you want to exclude the header row, just remove the line:

rowIter = sheet.rowIterator();

rowIter = sheet.rowIterator();

就在 while 循环之前.

just before the while loop.

这是您要找的吗?

这篇关于计算Excel表格一列中的行数(提供Java代码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆