douzhong5902 2019-03-15 17:56
浏览 59

由于编码错误而从PHPExcel下载文件时出错

I have a problem with the PHPExcel library, it is generating the file correctly and saving on the server, however it is not downloading any way directly on the site and it appears bad encoding, this started to cause after the server change. I have already changed some headers but with no success. I am using Excel5 with the xls extension

    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条回答 默认 最新

  • douzhuo8871 2019-05-10 12:56
    关注

    Just Use ob_end_clean() before $objWriter->save("download/".$filename);

    like

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

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起