使用Apache POI通过单元格引用字母标识符获取单元格。

17

我试图通过单元格引用从行中获取单元格,但遇到问题。例如,我有:

row.getCell(CellReference.convertColStringToIndex("B"));

如果列索引是1,那么这将很好地工作,但是如果删除了列,使得B列的索引变为2,并且方法:CellReference.convertColStringToIndex("B") 仍然将其转换为1,在这种情况下我无法获取我的列,我会得到null

所以问题是,如何根据单元格标识符(一个字母)从行中获取列?

3个回答

33

看一下我之前回答的一个问题:链接

你可能想要使用CellReference工具类来帮助您。它提供了Excel风格字母+数字引用和POI风格基于0的行+列之间的转换,当使用它时,您可以这样做:

 Sheet sheet = workbook.getSheet("MyInterestingSheet");

 CellReference ref = new CellReference("B12");
 Row r = sheet.getRow(ref.getRow());
 if (r != null) {
    Cell c = r.getCell(ref.getCol());
 }

这将允许您找到给定Excel样式引用的单元格(如果已定义,则为非空;否则为null)


-1

所有人:代码要求r1(第1行)必须与单元格实际所在的行号完全相同。 在此情况下,它是r36而不是r1。 请将所有r1更改为r36。 请原谅我的疏忽。


1
请编辑您之前的回答以添加细节(而不是添加新的回答)-在此过程中,您还可以修复命名违规问题 :) - kleopatra

-1

获取多行/列:

  CellReference ref1 = new CellReference("A36"); // First LINE 1
  CellReference ref2 = new CellReference("B36"); 
  CellReference ref3 = new CellReference("C36"); 
  CellReference ref4 = new CellReference("D36");

  XSSFRow r1 = sheet.getRow(ref1.getRow()); 
    if (r1 != null) {
            Cell a36 = r1.getCell(ref1.getCol());
            Cell b36 = r1.getCell(ref2.getCol());
            Cell c36 = r1.getCell(ref3.getCol());
            Cell d36 = r1.getCell(ref4.getCol());
            Cell e36 = r1.getCell(ref5.getCol());
                            
            AMT1 = a36.getStringCellValue();
            AMT2 = b36.getStringCellValue();
            AMT3 = c36.getStringCellValue();
            AMT4 = d36.getNumericCellValue();
            AMT5 = e36.getNumericCellValue();
            AMT5A = AMT5.intValue();
           }           

r1 是第一行。这将获取 xlsx 文件中第一行指定的条目并将其分配给一个变量(AMTx),如下所示。在 Java 文件的“public class ........”行后面放置变量指定。

  public static String AMT1;//Line 1 
  public static String AMT2;  
  public static String AMT3; 
  public static Double AMT4;  
  public static Double AMT5;  
  public static Integer AMT5A;  

请注意,Excel xlsx文件将数字存储为单元格中的Double类型 - 因此在AMT5A中需要进行整数转换。

请遵循Java命名规范,并且不要使用静态作用域。 - kleopatra

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