无法在 PHP Excel 中创建多个工作表

Posted

技术标签:

【中文标题】无法在 PHP Excel 中创建多个工作表【英文标题】:Not able to create multiple worksheet in PHP Excel 【发布时间】:2015-04-27 09:37:27 【问题描述】:

您好,我正在 php Excel 中创建多个工作表,但它不工作。 我面临一个问题“您试图通过越界索引设置一张活跃的工作表:1。实际的工作表数量为 1。”

这是我的代码:

function downloadReportInExcel($excelSheetDetails, $headers, $resultSetFields, $resultSetPointer) 
    /** Error reporting */
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);
    date_default_timezone_set('Asia/Calcutta');

    if (PHP_SAPI == 'cli')
        die('This example should only be run from a Web Browser');

    /** Include PHPExcel */
    require_once '../../lib/PHPExcel.php';


    // Create new PHPExcel object
    $objPHPExcel = new PHPExcel();

    //Enable cell caching and serialize it so that memory footprint is small and performance is high
    $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;
    PHPExcel_Settings::setCacheStorageMethod($cacheMethod);

    //Setting a default height for all rows
    $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);

    // Set document properties
    $objPHPExcel->getProperties()->setCreator($excelSheetDetails['createdBy']) //"Maarten Balliauw"
            ->setLastModifiedBy($excelSheetDetails['modifiedBy']) //"Maarten Balliauw"
            ->setTitle($excelSheetDetails['title']) //"Office 2007 XLSX Test Document"
            ->setSubject($excelSheetDetails['subject']) //"Office 2007 XLSX Test Document"
            ->setDescription($excelSheetDetails['description']) //"Test document for Office 2007 XLSX, generated using PHP classes."
            ->setKeywords("office 2007 openxml php")
            ->setCategory($excelSheetDetails['category']); //"Test result file"
    // Add data
    $i = 1;
    $j = 65;
    $length = count($headers);
    for ($count = 0; $count < $length; $count++) 
        //Add headers
        foreach ($headers[$count] AS $headerValue)
        
            //echo $headerValue;
            $objPHPExcel->setActiveSheetIndex($count)
                    ->setCellValue('' . chr($j) . $i . '', $headerValue);
            $objPHPExcel->getActiveSheet()->getColumnDimension(chr($j))->setAutoSize(true);
            $j++;
        
        //~ exit;
        $k = $j - 1;
        $i+= 1;
        $j = 65;

        $styleArray = array(
            'font' => array(
                'bold' => true,
            ),
            'alignment' => array(
                'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
            ),
        );
        $objPHPExcel->getActiveSheet()->getStyle(chr($j) . '1:' . chr($k) . '1')->applyFromArray($styleArray);

        foreach ($resultSetPointer[$count] AS $result)
        
            $resultKeyIndex = -1;
            //print_r($result);
            for ($counter = $j; $counter <= $k; $counter++)
            
                $objPHPExcel->setActiveSheetIndex($count)
                        ->setCellValue('' . chr($counter) . $i . '', $result[$resultSetFields[$count][++$resultKeyIndex]]);
                //echo $result[$resultKeyIndex].'<br />';
            
            $i++;
        
        //exit;
        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle($excelSheetDetails['worksheetTitle']); //"Simple"
        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex($count);
    
    //print_r($objPHPExcel);exit;
    // Redirect output to a client’s web browser (Excel5)
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="' . $excelSheetDetails['fileName'] . '.xls"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');

    // If you're serving to IE over SSL, then the following may be needed
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
    header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header('Pragma: public'); // HTTP/1.0

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');

    //Break cyclic references to clear worksheet from memory
    $objPHPExcel->disconnectWorksheets();
    unset($objPHPExcel);

    exit;

这里我提到了我在这个函数中传递的所有参数

for($count = 0; $count < $studentWiseAttendanceLen; $count++) 
    $finalArray[0][$count]['name']      = $studentWiseAttendance[$count]['student'];
    $finalArray[0][$count]['present']   = $studentWiseAttendance[$count]['presentPercentage'];
    $finalArray[0][$count]['absent']    = $studentWiseAttendance[$count]['absentPercentage'];
    $finalArray[0][$count]['late']      = $studentWiseAttendance[$count]['latePercentage'];
    $finalArray[0][$count]['overall']   = $studentWiseAttendance[$count]['overallPresent'];

for($count = 0; $count < $dateWiseAttendanceLen; $count++) 
    $finalArray[1][$count]['attendancedatetime']    = $dateWiseAttendance[$count]['attendanceTakenTime'];
    $finalArray[1][$count]['present']               = $dateWiseAttendance[$count]['presentPercentage'];
    $finalArray[1][$count]['absent']                = $dateWiseAttendance[$count]['absentPercentage'];
    $finalArray[1][$count]['late']                  = $dateWiseAttendance[$count]['latePercentage'];
    $finalArray[1][$count]['totalStudent']          = $dateWiseAttendance[$count]['totalStudent'];


//echo("<script>console.log('PHP: ". print_r($dateWiseAttendance) ."');</script>");
// Array fields
$resultSetFields[0] = array(
    'name',
    'present',
    'absent',
    'late',
    'overall'
);
$resultSetFields[1] = array(
    'attendancedatetime',
    'present',
    'absent',
    'late',
    'totalStudent'
);

// Excel details
$excelSheetDetails = array(
    'createdBy' => 'Admin',
    'modifiedBy' => 'Admin',
    'title' => $subjectName . ' Attendance Report',
    'subject' => 'Attendance Report',
    'description' => 'Attendance Report for students in percentage',
    'category' => 'Report file',
    'worksheetTitle' => 'Attendance Details',
    'fileName' => $subjectName . ' Attendance_Report'
);
// File headers
$headers[0] = array(
    'STUDENT NAME',
    'PRESENT(%)',
    'ABSENT(%)',
    'LATE(%)',
    'OVERALL PRESENT(%)'
);
$headers[1] = array(
    'CLASS TAKEN',
    'PRESENT(%)',
    'ABSENT(%)',
    'LATE(%)',
    'OVERALL STUDENT PRESENT'
);
downloadReportInExcel($excelSheetDetails, $headers, $resultSetFields, $finalArray);

【问题讨论】:

如果张数为1,索引不应该为0吗? 是的,但我想创建多个工作表 您是否编写了代码来添加另一张工作表?我在这里看不到任何东西。有很多来自快速谷歌的例子。 是的,我正在传递一个数组和数组的键数它应该决定工作表的数量 您的代码中没有调用addSheet()createSheet(),那么魔法应该发生在哪里? 【参考方案1】:

你需要

$objPHPExcel->createSheet();

新工作表之前

【讨论】:

以上是关于无法在 PHP Excel 中创建多个工作表的主要内容,如果未能解决你的问题,请参考以下文章

在 CSV 文件中创建多个工作表

如何在 Google 表格中创建多个工作表引用的 INDIRECT 数组字符串?

如何在excel中创建表格区域

将多个 csv 文件中的数据导入一个 Excel 工作表并计算平均值

如何拆分excel 多个工作表

如何使用多个 for 循环在 php 中创建 sql 语句