关于我之前的问题如何使用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();
}
}
}
for循环
来尝试整个工作表,但是没有得到期望的结果。你能否编辑答案并告诉我如何遍历具有10个列的工作表列表? - Vinayak Pahalwan