简体   繁体   English

在 Apache POI 中按文本查找 Excel 单元格

[英]Find Excel Cell by Text in Apache POI

I'd like to find a cell in an Excel sheet by its text.我想通过文本在 Excel 工作表中找到一个单元格。 The text is something like %t :文本类似于%t

sheet.findCell("%t"); // pseudo-code, not working

My goal is to enable the user to provide kind of template, in which data is written.我的目标是使用户能够提供一种模板,其中写入数据。 Colours and fonts, as well as data's position can be configured by the user in an Excel file.用户可以在 Excel 文件中配置颜色和字体以及数据的位置。 This %t cell is the top-left corner of the data table.这个%t单元格是数据表的左上角。

Additional question: Is there a more elegant way to get this job done?附加问题:有没有更优雅的方法来完成这项工作?

EDIT I'm iterating over the rows and cells to find it.编辑我正在遍历行和单元格以找到它。 I'm afraid it's not really efficient, but it works so far:恐怕它不是很有效,但到目前为止它有效:

public static Cell findCell(XSSFSheet sheet, String text) {     
    for(Row row : sheet) {          
        for(Cell cell : row) {              
            if(text.equals(cell.getStringCellValue()))
                return cell;
        }
    }       
    return null;
}

You can iterate through the cells of the sheet and investigate the contents.您可以遍历工作表的单元格并调查内容。 I don't think there is an easier method.我认为没有更简单的方法。

Its an old post but still i want to publish my code.它是一个旧帖子,但我仍然想发布我的代码。 You can define a file path.您可以定义文件路径。

String inputFile = "src\main\resources\file.xlsx";

XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(inputFile));
                DataFormatter formatter = new DataFormatter();
                for (XSSFSheet sheet : xssfWorkbook) {
                    for (Row row : sheet) {
                        for (Cell cell : row) {
                            if (formatter.formatCellValue(cell).contains("name")){
                                cell.setCellValue("test");
                            }
                        }
                    }
                }
                xssfWorkbook.write(new FileOutputStream(inputFile));

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

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