Updating existing Excel file in Java Apache POI

后端 未结 1 1245
执笔经年
执笔经年 2021-02-03 13:46

I\'m trying to write a Java program that will run daily (using a task scheduler) and will append a column to an Excel spreadsheet every time it runs. The problem I am having is

相关标签:
1条回答
  • 2021-02-03 14:09

    I think you are creating the new rows and cells again and again and causing the re-write of excel.

    Essentially you need to get the rows and cells instead of creating them in your program.

    HSSFRow row1 = worksheet.createRow(0);
    

    You may need to get the row instead of creating it.

    HSSFRow row1 = worksheet.getRow(0);
    

    https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Sheet.html#getRow(int)

    This small example updates the second cell of second row:

    //Read the spreadsheet that needs to be updated
    FileInputStream fsIP= new FileInputStream(new File("C:\\Excel.xls"));  
    //Access the workbook                  
    HSSFWorkbook wb = new HSSFWorkbook(fsIP);
    //Access the worksheet, so that we can update / modify it. 
    HSSFSheet worksheet = wb.getSheetAt(0); 
    // declare a Cell object
    Cell cell = null; 
    // Access the second cell in second row to update the value
    cell = worksheet.getRow(1).getCell(1);   
    // Get current cell value value and overwrite the value
    cell.setCellValue("OverRide existing value");
    //Close the InputStream  
    fsIP.close(); 
    //Open FileOutputStream to write updates
    FileOutputStream output_file =new FileOutputStream(new File("C:\\Excel.xls"));  
     //write changes
    wb.write(output_file);
    //close the stream
    output_file.close();
    
    0 讨论(0)
提交回复
热议问题