2

I have an existing excel sheet and I am trying to read it and put it in my list. But, there are merged cells so i wanted to unmerge before storing it in my list. I tried the removeMergedRegion() method but it didn't work. when i open the excel sheet after the process i wanted the cells to be unmerged. And if possible after the unmerge the empty cell should be deleted.

 public void newone(){
        //calling my existing excel file
        File file = new File("C:\\Users\\daisy\\Downloads\\What.xlsx");         
        FileInputStream fis;
        try {
            fis = new FileInputStream(file);
            Workbook workbook = new XSSFWorkbook(fis); 
            // Iterate through all merged region in the sheet
            Sheet sheet = workbook.getSheet("Sheet1");      
                for(int i=0; i < sheet.getNumMergedRegions(); i++)
                {
                    // Delete the region
                    sheet.removeMergedRegion(i);
                    System.out.println("Unmerged successfully");
                }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }          
    }
Olaf Kock
  • 46,930
  • 8
  • 59
  • 90

1 Answers1

0

I think the problem is, that your change has been done in memory only and was not saved. You need to save the modified sheet. To demonstrate I borrowed code from a different question Save Excel document Apache POI

try {
    FileOutputStream out = new FileOutputStream("C:\\Users\\...\\New.xlsx");
    workbook.write(out);
    out.close();
} catch (FileNotFoundException ex) {
    // handle the exception here
}

Off-topic - I strongly recommend to you not to swallow exceptions with catch(e) { e.printStackTrace(); }. There is lots of articles, that explain why it is a bad practice.

Jan Mares
  • 795
  • 10
  • 22