Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFWorkbook.java
Original file line number Diff line number Diff line change
Expand Up @@ -1061,11 +1061,30 @@ public HSSFSheet getSheetAt(int index) {
* If there are multiple matches, the first sheet from the list
* of sheets is returned.
*
* <p>
* Note that Excel limits sheet names to 31 characters. If you try to look up
* a sheet by a name longer than that, a warning will be logged, since
* such a sheet cannot exist in Excel and the lookup will likely return {@code null}.
* </p>
*
* @param name of the sheet
* @return HSSFSheet with the name provided or {@code null} if it does not exist
*/
@Override
public HSSFSheet getSheet(String name) {

if (name == null || name.isEmpty()) {
return null;
}

if(name.length() > MAX_SENSITIVE_SHEET_NAME_LEN) {
LOGGER.atWarn().log(
"Sheet lookup requested with name '{}' which exceeds Excel's {} character limit. " +
"Sheets are stored with truncated names, so this lookup will likely return null.",
name, MAX_SENSITIVE_SHEET_NAME_LEN
);
}

for (int k = 0; k < _sheets.size(); k++) {
String sheetname = workbook.getSheetName(k);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,24 @@ void sheetSerializeSizeMismatch_bug45066() throws IOException {
}
}

@Test
void searchSheetExceed31CharactersName() throws IOException {
String sheetName = "ThisIsAVeryLongSheetNameExceeding31Chars";

try (HSSFWorkbook wb = new HSSFWorkbook()) {
wb.createSheet(sheetName);

// Sheet name is truncated to 31 characters
Sheet sheetByOriginalName = wb.getSheet(sheetName);
assertNull(sheetByOriginalName, "Sheet lookup using original name >31 chars must return null");

// Truncated name SHOULD resolve
String truncated = sheetName.substring(0, 31);
Sheet sheetByTruncatedName = wb.getSheet(truncated);
assertNotNull(sheetByTruncatedName, "Sheet lookup using truncated name must return the sheet");
}
}

/**
* Checks that us and HSSFName play nicely with named ranges
* that point to deleted sheets
Expand Down