首页 文章

使用Apache poi编辑excel表

提问于
浏览
0

我正在尝试使用apache poi编辑excel表,我有一个包含2行和5列的工作表,如果第2行的第二个单元格为null,那么它应该添加第3行,但是我得到了一个类未找到异常,尽管UpdateXLS存在于我的D盘中 .

这是代码:

public class New {
public static void main(String[] args){
    try{
     InputStream inp = new FileInputStream("D:\\UpdateXLS.xls");
        //InputStream inp = new FileInputStream("workbook.xlsx");

        Workbook wb = WorkbookFactory.create(inp);
        Sheet sheet = wb.getSheetAt(0);
        Row row = sheet.getRow(2);
        Cell cell = row.getCell(2);
        if (cell == null)
            cell = row.createCell(3);
        cell.setCellType(Cell.CELL_TYPE_STRING);
        cell.setCellValue("a test");

        // Write the output to a file
        FileOutputStream fileOut = new FileOutputStream("UpdateXLS.xls");
        wb.write(fileOut);
        fileOut.close();
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

我该怎么办 ?

2 回答

  • 0

    问题似乎在于

    FileOutputStream fileOut = new FileOutputStream("UpdateXLS.xls");
    

    尝试用以下代码替换:

    FileOutputStream fileOut = new FileOutputStream("D:\\UpdateXLS.xls");
    
  • 1

    comment,我可以建议您在指定的路径上退出检查文件 .

    使用File

    File f = new File("D:\\UpdateXLS.xls");
    //check whether file exists or not to avoid any further exceptions
    if(f.exists()){
      Workbook wb = WorkbookFactory.create(f);
      Sheet sheet = wb.getSheetAt(0);
      Row row = sheet.getRow(2);
      ......
      .......
      ........
    }
    

    FileNotFoundException指示尝试打开由指定路径名表示的文件失败 . 当具有指定路径名的文件不存在时,FileInputStream,FileOutputStream和RandomAccessFile构造函数将抛出此异常 . 如果文件确实存在但由于某种原因无法访问,例如当尝试打开只读文件进行写入时,这些构造函数也会抛出它 .


    在编写文件时,请检查您的路径

    FileOutputStream fileOut = new FileOutputStream("UpdateXLS.xls");
    

    改成

    FileOutputStream fileOut = new FileOutputStream("D:\\UpdateXLS.xls");
    

相关问题