使用HSSF写入Excel时触发IndexOutOfBoundsException问题求助
Hey there! Let's figure out why you're running into that IndexOutOfBoundsException when writing your two String ArrayLists to Excel using HSSF. This is a super common pitfall, so let's break down the likely causes and how to fix them.
Common Causes & Solutions
1. Trying to Access Rows/Cells That Don't Exist
HSSF won't automatically create rows or cells for you. If you call sheet.getRow(rowIndex) on a row that hasn't been created yet, it returns null. Trying to create a cell on a null row will lead to errors, and even if that doesn't crash you, subsequent index operations can go haywire.
2. Mismatched ArrayList Sizes + Unchecked Index Access
If your two ArrayLists have different lengths, looping based on one list's size and trying to access the other list at the same index will trigger an out-of-bounds error once you exceed the shorter list's length.
Correct Implementation Example
Here's a robust way to write your ArrayLists to Excel without hitting exceptions:
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFRow; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; public class ExcelWriter { public static void main(String[] args) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Data"); // Your sample ArrayLists (could be different lengths) ArrayList<String> list1 = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry")); ArrayList<String> list2 = new ArrayList<>(Arrays.asList("Red", "Yellow")); // Loop up to the longest list's size to cover all elements int maxRowCount = Math.max(list1.size(), list2.size()); for (int rowIndex = 0; rowIndex < maxRowCount; rowIndex++) { // Create row if it doesn't exist yet HSSFRow row = sheet.getRow(rowIndex); if (row == null) { row = sheet.createRow(rowIndex); } // Write to first column only if index is within list1's bounds if (rowIndex < list1.size()) { row.createCell(0).setCellValue(list1.get(rowIndex)); } else { // Optional: Fill empty cells with blank or skip creating the cell row.createCell(0).setCellValue(""); } // Write to second column only if index is within list2's bounds if (rowIndex < list2.size()) { row.createCell(1).setCellValue(list2.get(rowIndex)); } else { row.createCell(1).setCellValue(""); } } // Write the workbook to file try (FileOutputStream outputStream = new FileOutputStream("output.xls")) { workbook.write(outputStream); workbook.close(); } catch (IOException e) { e.printStackTrace(); } } }
Key Fixes Explained
- Always check for null rows: Before creating cells, ensure the row exists with
sheet.createRow(rowIndex)ifsheet.getRow(rowIndex)returnsnull. - Handle mismatched list sizes: Use
Math.max()to get the longest list's length as your loop boundary. Then, check if the current index is within each list's bounds before accessing elements. - Optional empty cell handling: If one list is shorter, you can either fill the missing cells with blanks or skip creating them entirely—adjust based on your needs.
Debugging Tip
If you're still stuck, add print statements inside your loop to track the current index and list sizes:
System.out.println("Row index: " + rowIndex + " | List1 size: " + list1.size() + " | List2 size: " + list2.size());
This will help you see exactly when the index exceeds a list's length.
内容的提问来源于stack exchange,提问作者xXJohnRamboXx

