Search code examples
phpexport-to-excel

Output issues with PHPExcel


I have a web page where a user selects the amount of rows to be displayed followed by a button within a form that exports the data to excel.

<form method="post" action="">
     <input type="Submit" name="excel" value="Export" class="button">
</form>

I am able to get the data and put it into the excel file with the follwoing

if($_POST['excel']){
        $phpExcel = new PHPExcel();
        $styleArray = array(
            'font' => array(
            'bold' => true,
            )
        );
        //Get the active sheet and assign to a variable
        $foo = $phpExcel->getActiveSheet();

        //add column headers, set the title and make the text bold
        $foo->setCellValue("A1", "Nombre")
            ->setCellValue("B1", "Paterno")
            ->setCellValue("C1", "Pkey")
            ->setCellValue("D1", "Telefono")
            ->setCellValue("E1", "Ciudad")
            ->setCellValue("F1", "Used")
            ->setTitle("Contactos Encuestas")
            ->getStyle("A1:F1")->applyFromArray($styleArray);

        $xlsRow = 1;
        foreach ($rows as $column) {
            $foo->setCellValue("A".$xlsRow++, $column[2])
                ->setCellValue("B".$xlsRow++, $column[3])
                ->setCellValue("C".$xlsRow++, $column[0])
                ->setCellValue("D".$xlsRow++, $column[1])
                ->setCellValue("E".$xlsRow++, $column[5])
                ->setCellValue("F".$xlsRow++, $column[4]);
        }

        header("Content-Type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=\"ENcuestas_Contactos.xls\"");
        header("Cache-Control: max-age=0");

        $objWriter = PHPExcel_IOFactory::createWriter($phpExcel, "Excel5");
        $objWriter->save("php://output");
        $phpExcel->disconnectWorksheets();
        unset($phpExcel);
    }

This kinda works, the issue is that weird text allong with the webpage elements such as buttons and images get put onto the excel file.

What could be the issue?

is there a setting i'm missing?


Solution

  • Found out why I was getting HTML elements in the excel file.

    I had the PHP code within the HTML.

    Put the PHP Code outside the <html> code and voilà my excel file displayed without any issues.