#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2010
    Posts
    26
    Rep Power
    0

    Red face Can't set new sheetname after copied sheet successfully


    Hi Guys, here's my copy and setting new sheet name code for excel 2007 file below, which seems correct but sheet name doesn't change after copy successful. Any help or suggestions greatly appreciated, thanks.
    Code:
    // copy blank spreadsheet and create new client spreadsheet
    String sheetCopied = "no";
    String newFile = "";
    if (dirName.equals("C:\\testing")) {
    	FileSystem system = FileSystems.getDefault();
    	Path original = system.getPath(dirName+"\\blank.xlsx");
    	Path target = system.getPath(dirName+"\\"+clientName+".xlsx");
    	newFile = target.toString();
    	System.out.println("blank spreadsheet copied successfully");
    	
    	try {
    		// Throws an exception if the original file is not found.
    		Files.copy(original, target, StandardCopyOption.REPLACE_EXISTING);
    		
    		try (FileInputStream file2 = new FileInputStream(newFile)) {
    			workbook2 = new XSSFWorkbook(file2);
    			
    			// create new sheet
    			Sheet cloneSheet = workbook2.cloneSheet(0);
    			int cloneSheetCount = workbook2.getSheetIndex(cloneSheet); 
    			workbook2.setSheetName(cloneSheetCount, "new sheet");
    
    		}catch(Exception e) {
    			System.out.println("Copy sheet ERROR");
    		}
    	} catch (IOException ex) {
    		System.out.println("Copy file ERROR");
    	}                                
    }
  2. #2
  3. Lord of the Dance
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Oct 2003
    Posts
    4,206
    Rep Power
    2012
    You need to save changes back to the file.
    There is an example of that process here:
    https://www.concretepage.com/apache-...ng-poi-in-java

IMN logo majestic logo threadwatch logo seochat tools logo