| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 
 | public static void main(String[] args) {
		try {
			addRow(FILE_NAME, SHEET_NAME, 42, "blahblah", new Date(), 33.33, true);
		} catch (IOException e) { 
			e.printStackTrace();
		}
		try {
			addRows(FILE_NAME, SHEET_NAME, new Object[][] {
				{1, "truc"},
				{2, "bidule"},
				{3, "machin"}
			});
		} catch (IOException e) { 
			e.printStackTrace();
		}
	}
 
	public static void addRow(String fileName, String sheetName, Object...values) throws IOException {
 
		try(Workbook workbook=WorkbookFactory.create(new FileInputStream(fileName))) { 
		    Sheet sheet = workbook.getSheet(sheetName);
			addRow(sheet, values);
			try(FileOutputStream outputStream = new FileOutputStream(fileName)) {
				workbook.write(outputStream);
			}
		} catch (EncryptedDocumentException | InvalidFormatException e) {
			throw new IOException(e);
		}
 
	}
 
	public static void addRows(String fileName, String sheetName, Object[][] values) throws IOException {
 
		try(Workbook workbook=WorkbookFactory.create(new FileInputStream(fileName))) { 
		    Sheet sheet = workbook.getSheet(sheetName);
		    for(Object[] row : values) {
		    	addRow(sheet, row);
		    }
			try(FileOutputStream outputStream = new FileOutputStream(fileName)) {
				workbook.write(outputStream);
			}
		} catch (EncryptedDocumentException | InvalidFormatException e) {
			throw new IOException(e);
		}
 
	}
 
	/**
         * Ajoute les valeurs dans une nouvelle ligne en bas
         * @param sheet
         * @param values
         * @return
         */
	public static Row addRow(Sheet sheet, Object...values) {
		int rowNum = sheet.getLastRowNum(); 
	    if ( sheet.getRow(rowNum)!=null ) {
	    	rowNum++;
	    } 
	    return addRow(sheet, rowNum, values);
	}
 
	/**
         * Ecrit les valeurs dans la ligne de numéro spécifié
         * @param sheet
         * @param values
         * @return
         */
	public static Row addRow(Sheet sheet, int rowNum, Object...values) {
		Row row = sheet.createRow(rowNum);
		for(int i=0; i<values.length; i++) {
			Cell cell = row.createCell(i);
			Object value = values[i];
			if ( value instanceof String ) {
				cell.setCellValue((String)value);
			}
			else if ( value instanceof Boolean ) {
				cell.setCellValue((Boolean)value);
			}
			else if ( value instanceof Number ) {
				cell.setCellValue(((Number)value).doubleValue());
			}
			else if ( value instanceof Date ) {
				cell.setCellValue((Date)value);
			}  
		}
		return row;
	} | 
Partager