Excel文件在向其追加记录时崩溃

时间:2016-06-13 02:18:45

标签: java excel

我正在使用此代码将记录附加到excel文件,但此代码会崩溃现有文件而不是将记录附加到该文件。那么请告诉我如何将记录附加到我的Excel文件中?

代码:

public static void writeToExcel() {

        try {
            File file = new File("C:\\Users\\abc\\Desktop\\Selenium Tests.xlsx");
            FileOutputStream fos = new FileOutputStream(file,true);
            XSSFWorkbook  workbook = new XSSFWorkbook();            
            XSSFSheet sheet = workbook.createSheet("fund");  
            int rowNum = sheet.getLastRowNum()+1;
            Row row = sheet.createRow(rowNum);   
            Cell cell0 = row.createCell(0);
            cell0.setCellValue("Nav Value 1");
            Cell cell1 = row.createCell(1);
            cell1.setCellValue("Amount Change 1");       
            Cell cell2 = row.createCell(2);
            cell2.setCellValue("Percent Change 1");
            workbook.write(fos);
            fos.flush();
            fos.close();
            System.out.println("done");
        }
        catch (Exception exp) {
            exp.printStackTrace();
        }
    }

1 个答案:

答案 0 :(得分:0)

您已使用InputStream打开工作簿

  

InputStream fos = new FileInputStream(fileName);

并使用FileOutputStream写入文件。

  

FileOutputStream fileOut = new FileOutputStream(fileName);   workbook.write(FILEOUT);

无需在最后一行中添加1。

  

int rowNum = sheet.getLastRowNum()+ 1;

细胞基于0

  

Cell cell0 = row.createCell(0);

public static void writeToExcel() {

    try {

        try {
            String fileName = "C:\\Users\\best buy\\Downloads\\_temp.xlsx";
            InputStream fos = new FileInputStream(fileName);
            Workbook workbook = WorkbookFactory.create(fos);
            Sheet sheet = workbook.getSheet("fund");  
            int rowNum = sheet.getLastRowNum()+1;
            Row row = sheet.createRow(rowNum);   
            Cell cell0 = row.createCell(0);
            cell0.setCellValue("Nav Value 1");
            Cell cell1 = row.createCell(1);
            cell1.setCellValue("Amount Change 1");      
            Cell cell2 = row.createCell(2);
            cell2.setCellValue("Percent Change 1");
            // Write the output to a file
            FileOutputStream fileOut = new FileOutputStream(fileName);
            workbook.write(fileOut);
            fileOut.close();

            System.out.println("done");
        }
        catch (Exception exp) {
            exp.printStackTrace();
        }
    }
    catch (Exception exp) {
        exp.printStackTrace();
    }
}