简体   繁体   English

如何使用POI在Java中的Excel中获取单元格的名称?

[英]How to get a cell's name in Excel in java using POI?

I am trying to learn POI and I have a sample code. 我正在尝试学习POI,并且有一个示例代码。

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;

public class ExpressionExample {

    public static void main(String[] args) throws Exception {

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("Sample sheet");
        Row row = sheet.createRow(0);
        FormulaEvaluator evaluator = workbook.getCreationHelper()
                .createFormulaEvaluator();
        HSSFCell formulaCell = (HSSFCell) row.createCell(6);
        HSSFCell c1 = (HSSFCell) row.createCell(1);
        HSSFCell c2 = (HSSFCell) row.createCell(2);
        c1.setCellValue(5);
        c2.setCellValue(10);
        CellReference cr1 = new CellReference(0 , 1); 

        String line = "if(A1>A2, \"LAR\" , if(5>10, \"AB\" , \"CD\"))";
        formulaCell.setCellFormula(line);

        CellValue cellValue = evaluator.evaluate(formulaCell);
        System.out.println(cellValue.getStringValue());
    }

}

now in my formula I have applied values of cells A1 and A2, but I want to give this value based on my code and cells should be 'C1 and c2. 现在在公式中,我已经应用了单元格A1和A2的值,但是我想根据我的代码给出此值,单元格应该为'C1和c2。 any Idea how to do this ? 任何想法如何做到这一点?

It would be great help. 这将是极大的帮助。

I'm not sure if I have picked up your question correctly but here goes... 我不确定我是否正确回答了您的问题,但是这里...

If you are wanting to use the values to which you are setting into the cells c1 and c2 (in this case '5' & '10') in your formula, you can create 2 int objects to hold these values: 如果要在公式的单元格c1c2使用要设置的值(在本例中为“ 5”和“ 10”),则可以创建2个int对象来保存这些值:

int c1Value = 5;
int c2Value = 10;

You can then use these objects to set the cell values and also include them in your formula: 然后,您可以使用这些对象来设置单元格值,并将它们包括在公式中:

c1.setCellValue(c1Value); 
c2.setCellValue(c2Value);

String line = "if(" + c1Value + ">" + c2Value + ", \"LAR\" , if(5>10, \"AB\" , \"CD\"))";

Also note, in your code c1 refers to the cell A2 in Excel, and c2 refers to cell A3 . 还要注意,在您的代码中, c1引用Excel中的单元格A2 ,而c2引用单元格A3 Both rows and columns start at 0 in Apache. 在Apache中,行和列都从0开始。

Is this what you are trying to do? 这是您要做什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM