2013-02-15 18 views
1

我处于困境中。我一直试图通过Java中的hs​​sf/xssf将数据写入现有的excel文件。我没有错误,但仍然在运行时无法更改Excel表格。任何人都可以帮我解决这个问题吗?我的代码是:通过hssf/xssf将数据写入现有的excel中的单元格。

try { 
    FileInputStream inp = new FileInputStream("C:/Users/Training/Desktop/saurav.xlsx"); 


      Workbook wb = null; 
      try { 
       wb = WorkbookFactory.create(inp); 
      } catch (InvalidFormatException e) { 
       e.printStackTrace(); 
      } 
      Sheet sheet = wb.getSheetAt(0); 
      Row row = sheet.getRow(3); 
      Cell cell = row.getCell(4); 
      if (cell == null) 
       cell = row.createCell(4); 
      cell.setCellType(Cell.CELL_TYPE_STRING); 
      cell.setCellValue("a test"); 

      // Write the output to a file 
      FileOutputStream fileOut = new FileOutputStream("C:/Users/Training/Desktop/saurav.xlsx"); 
      wb.write(fileOut); 
      fileOut.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

有人请帮我解决这个问题。从最近2天开始试验。

回答

2

而不是使用这个,它在我的系统中工作。

try { 
FileInputStream inp = new FileInputStream("C:/Users/Training/Desktop/saurav.xlsx"); 


     Workbook wb = null; 
     try { 
      wb = WorkbookFactory.create(inp); 
     } catch (InvalidFormatException e) { 
      e.printStackTrace(); 
     } 
     Sheet sheet = wb.getSheetAt(0); 
     Row row = sheet.getRow(3); 
     Cell cell = row.getCell(4); 
      cell = row.createCell(4); 
     cell.setCellType(Cell.CELL_TYPE_STRING); 
     cell.setCellValue("a test"); 

     // Write the output to a file 
     FileOutputStream fileOut = new FileOutputStream("C:/Users/Training/Desktop/saurav.xlsx"); 
     wb.write(fileOut); 
     fileOut.close(); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

也确保您在每次运行后刷新excel文件。

相关问题