Java读取excel

我正在尝试读取由4列和1行组成的示例文件。 下面的代码是为了testing我使用的API,即Apache POI ..

package testjavaexcel; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; /** * */ public class TestJavaExcel { /** * @param args the command line arguments */ public static void main(String[] args) { try { FileInputStream fileInputStream = new FileInputStream("poi-test.xls"); HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream); HSSFSheet worksheet = workbook.getSheet("POI Worksheet"); HSSFRow row1 = worksheet.getRow(0); HSSFCell cellA1 = row1.getCell((short) 0); String a1Val = cellA1.getStringCellValue(); HSSFCell cellB1 = row1.getCell((short) 1); String b1Val = cellB1.getStringCellValue(); HSSFCell cellC1 = row1.getCell((short) 2); boolean c1Val = cellC1.getBooleanCellValue(); HSSFCell cellD1 = row1.getCell((short) 3); Date d1Val = cellD1.getDateCellValue(); System.out.println("A1: " + a1Val); System.out.println("B1: " + b1Val); System.out.println("C1: " + c1Val); System.out.println("D1: " + d1Val); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } 

来自行“ HSSFRow row1 = worksheet.getRow(0); ”输出的错误是:

线程“main”中的exceptionjava.lang.NullPointerException at testjavaexcel.TestJavaExcel.main(TestJavaExcel.java:28)Java结果:1

不知道为什么发生这种情况…这似乎是直截了当forward.note所调用的.getCell()方法都罢工指示不推荐使用的方法,但不知道如何可以replace他们给API。

谢谢,

更新:我想通过新的方法,如果getCell采用int而不是旧版本使用短型。 修复了弃用的警告。 其余的问题仍未解决。 另外我使用poi版本3.8

检查你的Excel书籍是否必须有名称为“POI Worksheet”(确切名称)的表格。