使用Apache poi编辑excel表格
我想编辑一个Excel表使用Apache poi,我有一个工作表有2行和5列,如果行2的第二个单元格为空,那么它应该添加第三行,但我得到一个类没有发现exception,虽然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(); } }
我该怎么办 ?
从评论 ,我可以build议你,检查文件退出指定的path。
使用文件
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); ...... ....... ........ }
FileNotFoundExceptionexception
表示尝试打开由指定的path名表示的文件失败。
当具有指定path名的文件不存在时 ,FileInputStream,FileOutputStream和RandomAccessFile构造函数将引发此exception。
如果文件存在但由于某种原因无法访问 ,例如当试图打开只读文件进行写入时,也会由这些构造函数抛出。
当你正在写一个文件检查你的path
FileOutputStream fileOut = new FileOutputStream("UpdateXLS.xls");
改成
FileOutputStream fileOut = new FileOutputStream("D:\\UpdateXLS.xls");
问题似乎在
FileOutputStream fileOut = new FileOutputStream("UpdateXLS.xls");
尝试用以下命令replace该行:
FileOutputStream fileOut = new FileOutputStream("D:\\UpdateXLS.xls");