该进程无法访问该文件,因为它正在被另一个进程使用

我试图从一张excel文件读取数据,并写入其他同一excel文件的表。我试过这个:

FileInputStream file = new FileInputStream(new File("E:\\excel\\input.xlsx")); //Create Workbook instance holding reference to .xlsx file XSSFWorkbook workbook = new XSSFWorkbook(file); //Get first/desired sheet from the workbook XSSFSheet sheet = workbook.getSheetAt(0); //Iterate through each rows one by one Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); //For each row, iterate through all the columns Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); //Check the cell type and format accordingly switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: System.out.print((int)cell.getNumericCellValue()+ " "); break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue()); break; } } System.out.println(""); } file.close(); CreationHelper createHelper = workbook.getCreationHelper(); XSSFSheet newSheet = workbook.createSheet("new sheet"); // Create a row and put some cells in it. Rows are 0 based. Row row = newSheet.createRow((short)0); // Create a cell and put a value in it. Cell cell = row.createCell(0); cell.setCellValue(1); // Or do it on one line. row.createCell(1).setCellValue(1.2); row.createCell(2).setCellValue( createHelper.createRichTextString("This is a string")); row.createCell(3).setCellValue(true); System.out.println("writing to file"); // Write the output to a file FileOutputStream fileOut = new FileOutputStream(new File("E:\\excel\\input.xlsx")); workbook.write(fileOut); fileOut.close(); 

我已经成功地从excel表格中读取数据但是在写入下面给出的新表格的时候,我得到了exception

 java.io.FileNotFoundException: E:\excel\input.xlsx (The process cannot access the file because it is being used by another process) 

当“input.xlsx”文件已经被另一个应用程序打开时,当你试图执行这个程序的时候会发生这种情况。

请closuresMS Excel的任何实例,并尝试再次运行它

只是一个猜测,但XSSFWorkbook应该实现可closures,因此它有一个.close()应该被调用。 也许文件结果仍然在使用,因为这一点? 您可能需要一个中间步骤:写入新文件,closuresXSSFWorkbook,然后将新文件复制到您想要写入的旧文件