首页 > 解决方案 > 如何有条件地在电子表格上添加一列?

问题描述

如何有条件地添加电子表格列,例如用户是否想要包含特定列?我做了这个代码:

$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");

现在,例如,如果用户只想要收件人 #收件人姓名等。我怎样才能实现这样的功能?

标签: phpspreadsheetxlsx

解决方案


您将需要使用if条件,然后使用逻辑来准确计算单元格位置。

    $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");                                             

推荐阅读