phpexcel库在localhost上工作正常但在服务器中生成空白的excel文件

时间:2016-10-13 11:19:33

标签: php codeigniter phpexcel

这是我的代码在localhost中可以很好地生成包含来自数据库的数据的excel文件,但是在托管服务器中它会生成一个空白的excel文件:

// Starting the PHPExcel library
            $this->load->library('PHPExcel');
            //$this->load->library('PHPExcel/IOFactory');

            $objPHPExcel = new PHPExcel();
            $objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
            $objPHPExcel->setActiveSheetIndex(0);

            // Field names in the first row
            $fields = $query->list_fields();
            $col = 0;
            foreach ($fields as $field)
            {
                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
                $col++;
            }

            //format the column sizes 
            $sheet = $objPHPExcel->getActiveSheet();
            $cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells( true );
            /** @var PHPExcel_Cell $cell */
            foreach( $cellIterator as $cell ) {
                    $sheet->getColumnDimension( $cell->getColumn() )->setAutoSize( true );
            }

            //var_dump($query->result());
            //die;

            // Fetching the table data
            $row = 2;
            foreach($query->result() as $data)
            {
                $col = 0;
                foreach($fields as $field)
                {
                    $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
                    $col++;
                }

                $row++;
            }

            $objPHPExcel->setActiveSheetIndex(0);
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');


            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="01simple.xlsx"');
            header('Cache-Control: max-age=0');

            ob_clean();
            $objWriter->save('php://output');

1 个答案:

答案 0 :(得分:4)

我认为问题与phpexcel无关。我之前遇到过类似的问题,后来发现CI的list_fields()函数在某些linux服务器上不起作用。您可以通过静态放置字段名称而不是使用此功能来检查此方面。