我正在编写一个Java代码,它从Excel工作表中读取数据并在Jframe中显示内容。为此,我使用 apache-poi。这是我的代码
public static String fileToBeRead="/online.exam/Read.xls";
private void formWindowActivated(java.awt.event.WindowEvent evt) {
try{
// TODO add your handling code here:
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));
// Refer to the sheet. Put the Name of the sheet to be referred from
// Alternative you can also refer the sheet by index using getSheetAt(int index)
HSSFSheet sheet = workbook.getSheet("Sheet1");
//Reading the TOP LEFT CELL
HSSFRow row = sheet.getRow(0);
// Create a cell ate index zero ( Top Left)
HSSFCell cell = row.getCell(0);
// Type the content
System.out.println("THE TOP LEFT CELL--> " + cell.getStringCellValue());
}
catch(IOException ex){
System.err.println("No such file");
}
我无法读取该文件。请告诉我如何解决这个问题。
最佳答案
我不使用 Netbeans,但据我认为在某些情况下它显示出与 Eclipse 相同的行为。
尝试
public static String fileToBeRead="src/online/exam/Read.xls";
为什么:
- /online.exam/Read.xls 将转换为 C:\online.exam\Read.xls。保留第一个斜杠会使路径相对于工作目录(屏幕截图中的 Online.Exam 根目录)
- src 因为我猜 Netbeans 也在子目录中分离了源代码和二进制文件。更好的方法可能是将 Read.xls 放入与库和源包同一级别的目录“data”中(那么路径将是 data/Read.xls)。
- online/exam 而不是 online.exam,因为 online exam 是包名称,分为 2 个目录
关于java - 无法使用 Netbeans 从当前目录中的 Java 文件打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33391350/