Ошибка при загрузке файла из PHPExcel из-за плохой кодировки - PullRequest
1 голос
/ 15 марта 2019

У меня проблема с библиотекой PHPExcel, она правильно генерирует файл и сохраняет его на сервере, однако не загружает его напрямую на сайт и, по-видимому, неправильно кодирует, это стало причиной после смены сервера. Я уже изменил некоторые заголовки, но безуспешно. Я использую Excel5 с расширением xls

    public function export(){
    $dir = "download";
    $dh  = opendir($dir);
    $now = new DateTime();
    while (false !== ($filename = readdir($dh))){
        if(preg_match("/^filiadas\-[nacional|ac|al|am|ap|ba|ce|df|es|go|ma|mg|ms|mt|pa|pb|pe|pi|pr|rj|rn|ro|rr|rs|sc|sp|to].*\d{4}\-\d{2}\-\d{2}\.xls$/", $filename, $matches)){
            //exclui arquivo criado a mais de 12 horas atrás
            if(($now->getTimestamp() - filemtime($dir . "/" . $filename))>(60*60*12)){
                $path_file = dirname(dirname(dirname(dirname(__FILE__)))) . "/download/" . $filename;

                if(file_exists($path_file)){
                    unlink($path_file);
                }
            }
        }
    }

    set_time_limit(0);
    ini_set('memory_limit', '-1');



    $data = array();
    $fields = $this->filiadas->getFields();
    $options = $this->filiadas->getOptions();
    if(isset($_GET["unidas_uf"])){
        $this->filiadas->setData(
            array("unidas_uf" => strtoupper($_GET["unidas_uf"]))
        );
    }

    $this->filiadas->get();
    $this->aObjData->filiadas = $this->filiadas->get();

    //load our new PHPExcel library
    $this->load->library('excel');
    //activate worksheet number 1
    $this->excel->setActiveSheetIndex(0);
    //name the worksheet
    $this->excel->getActiveSheet()->setTitle('Filiadas');
    //set cell A1 content with some text
    //$this->excel->getActiveSheet()->setCellValue('A1', 'Filiadas');
    //change the font size
    //$this->excel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
    //make the font become bold
    //$this->excel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
    //merge cell A1 until D1
    //$this->excel->getActiveSheet()->mergeCells('A1:AD1');

    //$this->excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

    $pColumn=0;
    $pRow=1;

    foreach($fields as $field){

        $this->excel->getActiveSheet()->setCellValueByColumnAndRow($pColumn,$pRow,$field);
        $this->excel->getActiveSheet()->getColumnDimensionByColumn($pColumn)->setAutoSize(true);

        $this->excel->getActiveSheet()->getStyleByColumnAndRow( $pColumn, $pRow )->getFont()->setBold(true);
        $pColumn++;
    }

    //$this->excel->getActiveSheet()->fromArray($this->aObjData->filiadas, ' ', 'A2');
    foreach( $this->aObjData->filiadas as $filiada ){
        $pColumn=0;
        $pRow++;
        //$aFiliada = "";//get_object_vars($filiada);

        //nat_juridica_sub
        if ( array_key_exists( $filiada[ 'nat_juridica_sub' ], $options[ 'nat_juridica_sub1' ] ) )
            $filiada[ 'nat_juridica_sub' ] = $options[ 'nat_juridica_sub1' ][ $filiada[ 'nat_juridica_sub' ] ];
        else if ( array_key_exists( $filiada[ 'nat_juridica_sub' ], $options[ 'nat_juridica_sub2' ] ) )
            $filiada[ 'nat_juridica_sub' ] = $options[ 'nat_juridica_sub2' ][ $filiada[ 'nat_juridica_sub' ] ];

        //nat_juridica
        if( isset( $filiada[ 'nat_juridica' ] ) && array_key_exists( $filiada[ 'nat_juridica' ], $options[ 'nat_juridica' ] ) )
            $filiada[ 'nat_juridica' ] = $options[ 'nat_juridica' ][ $filiada[ 'nat_juridica' ] ];

        //tipo_plano
        if( isset( $filiada[ 'tipo_plano' ] ) && array_key_exists( $filiada[ 'tipo_plano' ], $options[ 'tipo_plano' ] ) )
            $filiada[ 'tipo_plano' ] = $options[ 'tipo_plano' ][ $filiada[ 'tipo_plano' ] ];

        //segmento
        if( isset( $filiada[ 'segmento' ] ) && array_key_exists( $filiada[ 'segmento' ], $options[ 'segmento' ] ) )
            $filiada[ 'segmento' ] = $options[ 'segmento' ][ $filiada[ 'segmento' ] ];

        //especie
        if( isset( $filiada[ 'especie' ] ) && array_key_exists( $filiada[ 'especie' ], $options[ 'especie' ] ) )
            $filiada[ 'especie' ] = $options[ 'especie' ][ $filiada[ 'especie' ] ];

        //rede_credenciada
        if( isset( $filiada[ 'rede_credenciada' ] ) )
        {
            $rede_credenciada = '';
            $indexes = explode( ',', $filiada[ 'rede_credenciada' ]);
            foreach($indexes as $index)
            {
                if ( array_key_exists( $index, $options[ 'rede_credenciada' ] ) )
                $rede_credenciada.= $options[ 'rede_credenciada' ][ $index ] . ',';
            }
            $filiada[ 'rede_credenciada' ] = trim($rede_credenciada, ",");
        }
        //custeio
        if( isset( $filiada[ 'custeio' ] ) )
        {
            $custeio = '';
            $indexes = explode( ',', $filiada[ 'custeio' ]);
            foreach($indexes as $index)
            {
                if ( array_key_exists( $index, $options[ 'custeio' ] ) )
                $custeio.= $options[ 'custeio' ][ $index ] . ',';
            }
            $filiada[ 'custeio' ] = trim($custeio, ",");
        }

        //contribuicao
        if( isset( $filiada[ 'contribuicao' ] ) )
        {
            $contribuicao = '';
            $indexes = explode( ',', $filiada[ 'contribuicao' ]);
            foreach($indexes as $index)
            {
                if ( array_key_exists( $index, $options[ 'contribuicao' ] ) )
                $contribuicao.= $options[ 'contribuicao' ][ $index ] . ',';
            }
            $filiada[ 'contribuicao' ] = trim($contribuicao, ",");
        }


        foreach($fields as $field){
            $this->excel->getActiveSheet()->setCellValueByColumnAndRow($pColumn,$pRow,$filiada[$field]);

            if(!empty($filiada["filiada_data_desfiliacao"]) && $filiada["filiada_data_desfiliacao"]!="0000-00-00"){
                $this->excel->getActiveSheet()->getStyleByColumnAndRow($pColumn,$pRow)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('FF9999');
            }

            $pColumn++;
        }

    }

    $this->excel->getActiveSheet()->calculateColumnWidths();


    $filename = "filiadas-" . (isset($_GET["unidas_uf"])?(empty($_GET["unidas_uf"])?"nacional":strtolower($_GET["unidas_uf"]))."-":"") . date("Y-m-d"). ".xls"; //save our workbook as this file name
    //save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
    //if you want to save it as .XLSX Excel 2007 format
    $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
    $objWriter->save("download/".$filename);
    //$this->excel->getActiveSheet()->unfreezePane();
    //force user to download the Excel file without writing it to server's HD
    //$objWriter->save('php://output');

    /*
    $cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
    $cacheSettings = array( 'memoryCacheSize' => '8MB');

    if (!PHPExcel_Settings::setCacheStorageMethod($cacheMethod,$cacheSettings))
    die('CACHEING ERROR');
    */

    header('Content-Type: application/vnd.ms-excel'); //mime type
    header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
    header('Cache-Control: max-age=0'); //no cache
    readfile("download/".$filename);
    exit();
}

1 Ответ

0 голосов
/ 10 мая 2019

Просто используйте ob_end_clean () перед $ objWriter-> save ("download /".$ filename);

как

$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
ob_end_clean();
$objWriter->save("download/".$filename);
...