Search code examples
phpspreadsheetxlsx

How to conditionally add a column on spreadsheet?


How can i add spreadsheet column conditionally, such as if the user wants to include particular column? I made this code:

$spreadsheet->getActiveSheet()
        ->setCellValue('A1', "SAMPLE HEADING")
        ->setCellValue('A2', "Sampling Report")
        ->setCellValue('A3', Date::PHPToExcel($dateTimeNow))
        ->setCellValue('A4', "Recipient #")
        ->setCellValue('B4', "Recipient Name")
        ->setCellValue('C4', "Date of Birth")
        ->setCellValue('D4', "Gender");

Now, if for example the user wants only Recipient # or Recipient Name etc. How can i achieve such functionality?


Solution

  • You will need to use if conditions and then use logic to calculate the cell position accurately.

        $alphas = range('A', 'Z'); //Delcare Range
        $includeRecipient = true;   // Flag to decide if Recipient # is requierd
        $includeRecipientName = false; // Flag to decide if Recipient Name is not required
    
    
        $spreadsheet->getActiveSheet()
            ->setCellValue('A1', "SAMPLE HEADING")
            ->setCellValue('A2', "Sampling Report")
            ->setCellValue('A3', Date::PHPToExcel($dateTimeNow));
    
    
        $cell = '';
    
        if( $includeRecipient ) {
            //Can move the following block in a function
            if (empty ( $cell) ) {
                $cell = current($alphas); //Gives A if empty
            } else {
                $cell = next($alphas); //Will give next in $range
            }
            $spreadsheet->setCellValue( $cell . '4', "Recipient #")
        }
    
        if( $includeRecipientName ) {
            if (empty ( $cell) ) {
                $cell = current($alphas); //Gives A if empty
            } else {
                $cell = next($alphas); //Will give next value in $range
            }
            $spreadsheet->setCellValue( $cell . '4', "Recipient Name")
        }
    
        if (empty ( $cell) ) {
            $cell = current($alphas); //Gives A if empty
        } else {
            $cell = next($alphas); //Will give next value in $range
        }   
    
    
        $spreadsheet->setCellValue('C4', "Date of Birth")
            ->setCellValue('D4', "Gender");