public static void main(String[] args) throws IOException { Workbook workbook = WorkbookFactory.create(new File("lib/1.xlsx")); Sheet sheet = workbook.getSheetAt(0); int rowCount = sheet.getLastRowNum() + 1; int colCount = sheet.getRow(0).getLastCellNum(); int cellWidth = 100 / colCount; int cellHeight = 100 / rowCount; StringBuilder html = new StringBuilder(); html.append("<table>"); for (int i = 0; i < rowCount; i++) { html.append("<tr>"); for (int j = 0; j < colCount; j++) { Cell cell = sheet.getRow(i).getCell(j); String value = cell.getStringCellValue(); html.append("<td style="width: " + cellWidth + "%; height: " + cellHeight + "%;">"); html.append(value); html.append("</td>"); } html.append("</tr>"); } html.append("</table>"); FileOutputStream fos = new FileOutputStream("lib/output.html"); fos.write(html.toString().getBytes()); fos.close();提示错误Exception in thread "main" java.lang.NullPointerException at a.b.main(b.java:26)第26行是Cell cell = sheet.getRow(i).getCell(j);
时间: 2023-11-27 07:49:36 浏览: 61
这个错误通常是因为在获取行或单元格时,没有检查它们是否为 null 引用。你可以尝试在访问行或单元格之前先检查它们是否为 null,如果是 null,则可能是因为该行或单元格为空。以下是一个示例代码片段,可以用于检查并避免 NullPointerException 错误:
```
for (int i = 0; i < rowCount; i++) {
Row row = sheet.getRow(i);
if (row != null) {
html.append("<tr>");
for (int j = 0; j < colCount; j++) {
Cell cell = row.getCell(j);
if (cell != null) {
String value = cell.getStringCellValue();
html.append("<td style='width: " + cellWidth + "%; height: " + cellHeight + "%;'>");
html.append(value);
html.append("</td>");
}
}
html.append("</tr>");
}
}
```
在这个示例代码中,我们在访问每一行和单元格之前,都先检查了它们是否为 null 引用,如果是 null,则跳过该行或单元格。这样可以避免 NullPointerException 错误。
阅读全文