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

时间:2016-07-20 07:37:54

标签: java excel apache-poi

我正在尝试从一张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表格中的数据但是我在写下面的新表格时遇到异常

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

2 个答案:

答案 0 :(得分:3)

当你试图在&#34; input.xlsx&#34;文件已被另一个应用程序打开。

请关闭任何MS Excel实例并尝试再次运行

答案 1 :(得分:0)

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