Если ваше «somevalue» является строкой, вы можете использовать этот код:
String path = "src/test.xlsx";
String param = "somevalue";
try (FileInputStream in = new FileInputStream(path);
XSSFWorkbook w = new XSSFWorkbook(in)) {
List<Integer> lst = new ArrayList<>();
SharedStringsTable table = w.getSharedStringSource();
for (int i = 0; i < table.getCount(); i++) {
if (table.getItemAt(i).toString().contains(param)) {
lst.add(i);
}
}
XSSFSheet s = w.getSheetAt(0);
String xml = s.getCTWorksheet().xmlText();
for (Integer i : lst) {
Pattern p = Pattern.compile("(?<=<main:c r=\")[A-Z0-9]+(?=\" t=\"s\"><main:v>" + i + "</main:v>)");
Matcher m = p.matcher(xml);
if(m.find()) {
System.out.println(m.group());
}
}
}
Приведенный выше код распечатает адрес любой ячейки, содержащей «somevalue».
Объяснение:
Предположим, что лист Excel выглядит следующим образом:
https://i.stack.imgur.com/IPQUB.jpg
Значения строковых ячеек хранятся в виде списка в workbook.SharedStringSource.Итак, во-первых, вам нужно проверить, какое значение ячейки содержит нужное вам «somevalue» и получить индекс этого значения.
В этом случае значения:
John: 0
Smith: 1
Том: 2
Сам лист имеет формат xml, как показано ниже:
<xml-fragment mc:Ignorable="x14ac" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">
<main:dimension ref="A1:C3" xmlns:main="http://schemas.openxmlformats.org/spreadsheetml/2006/main"/>
<main:sheetViews xmlns:main="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<main:sheetView tabSelected="1" workbookViewId="0"/>
</main:sheetViews>
<main:sheetFormatPr defaultRowHeight="15" x14ac:dyDescent="0.25" xmlns:main="http://schemas.openxmlformats.org/spreadsheetml/2006/main"/>
<main:cols xmlns:main="http://schemas.openxmlformats.org/spreadsheetml/2006/main"/>
<main:sheetData xmlns:main="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<main:row r="1" spans="1:3" x14ac:dyDescent="0.25">
<main:c r="A1" t="s">
<main:v>0</main:v>
</main:c>
</main:row>
<main:row r="2" spans="1:3" x14ac:dyDescent="0.25">
<main:c r="B2" t="s">
<main:v>1</main:v>
</main:c>
</main:row>
<main:row r="3" spans="1:3" x14ac:dyDescent="0.25">
<main:c r="C3" t="s">
<main:v>2</main:v>
</main:c>
</main:row>
</main:sheetData>
<main:pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3" xmlns:main="http://schemas.openxmlformats.org/spreadsheetml/2006/main"/>
</xml-fragment>
Вы можете видеть, что ячейка представлена в виде:
<main:c r="[CellAddress]" t="s">
<main:v>[workbook.SharedStringSource.index]</main:v>
</main:c>
Так что, если вы уже знаете индекс, вы можете использовать регулярное выражениеизвлечь адрес ячейки прямо из листа xml.