0

I'm making a Web portal my the company that i'm working. Now, i'm stuck in generating an excel report using PhpSpreadSheet. I cannot download the file instead just saving the excel file from where my phpfile is located. But if i call this file in my url 'Get_summary_excel.php' it will download.

this is my code in 'Get_summary_excel.php'

require "../../action/connection.php"; require '../API/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\Style\Border;
// error_reporting(E_ALL);


$filename = "userReports";
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();


$headerstyle = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => '000000'),
        'size'  => 12,
        'name'  => 'Verdana'
    ),
    'alignment' => array(
            'horizontal' => \PHPOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
    )
    );

$company_name_style = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => '000000'),
        'size'  => 10,
        'name'  => 'Verdana'
    ),
    'alignment' => array(
        'horizontal' => \PHPOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
        'vertical' => \PHPOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
    )
    );

$titlestyle = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => '000000'),
        'size'  => 14,
        'name'  => 'Verdana'
    ),
    'alignment' => array(
            'horizontal' => \PHPOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
    )
    );

$titledatestyle = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => '000000'),
        'size'  => 10,
        'name'  => 'Verdana'
    )
    );

$titleborder = array(
    'borders' => array(
    'allBorders' => array(
          'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, //BORDER_THIN BORDER_MEDIUM BORDER_HAIR
          'color' => array('rgb' => '000000')
    )
  )
);

$contentstyle = array(
    'alignment' => array(
        'vertical' => \PHPOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_TOP,
        'horizontal' => \PHPOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT,
    )
    );


    $sheet->mergeCells('B1:D2');
    $sheet->mergeCells('B5:D6');
    $sheet->mergeCells('B7:D7');

    $sheet->setCellValue('B1',"KABUKLOD SA KAUNLARAN CREDIT, INC.");
    $sheet->setCellValue('B5',"REPORT");
    $sheet->setCellValue('B7',date("M d Y"));
    $sheet->setCellValue('B9', 'Subject')
          ->setCellValue('C9', 'Datetime')
          ->setCellValue('D9', 'Status');

    foreach(range('B','D') as $columnID) {
        $sheet->getColumnDimension($columnID)->setAutoSize(true);
    }

        $string =   "solved,pending";
        $array  =   array_map("strval",explode(',', $string));
        $array  =   implode("','",$array);

        $query  =   "SELECT * FROM tbl_concern WHERE status IN ('".$array."') ORDER BY status";
        $stmt = $con->prepare($query);
        $stmt->execute();
        $result = $stmt->get_result();

        $counter = 10;
        while($row = $result->fetch_array()){
            $sheet->setCellValue('B'.$counter, ''.$row['subject'])
                ->setCellValue('C'.$counter, ''.$row['datetime'])
                ->setCellValue('D'.$counter, ''.$row['status']);
                $counter++;
                //   $sheet->getRowDimension(6)->setRowHeight(40);
        }

    $sheet->getColumnDimension('B')->setAutoSize(false);
    $sheet->getColumnDimension('D')->setAutoSize(false);
    $sheet->getColumnDimension('B')->setWidth(30);
    $sheet->getColumnDimension('D')->setWidth(20);
    // $sheet->getRowDimension('4')->setRowHeight(20);
    $sheet->getStyle('B1')->applyFromArray($company_name_style);
    $sheet->getStyle('B9:B'.$sheet->getHighestRow())->getAlignment()->setWrapText(true);
    $sheet->getStyle('B5')->applyFromArray($titlestyle);
    $sheet->getStyle('B7')->applyFromArray($titledatestyle);
    $sheet->getStyle('B5:D7')->applyFromArray($titleborder);
    $sheet->getStyle('C5:D'.$sheet->getHighestRow())->applyFromArray($contentstyle);
    $sheet->getStyle('B9:D9')->applyFromArray($headerstyle);
    $sheet->getStyle('B9:D9')->getFont()->setBold(true);
    $sheet->setShowGridLines(false);



    $spreadsheet->getActiveSheet()->setTitle('userReport');

    $spreadsheet->setActiveSheetIndex(0);

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

    $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->save('php://output');
    exit;

this is my javascript

$.ajax({
    type: "GET",
    url: "../phpfile/GET_summary_excel.php",
    data: "solved=" + d_solved + "&ongoing=" + d_ongoing + "&pending=" + 
    d_pending + "&fileformat=" + type,
    beforeSend: function () {

    },
    success: function (msg) {
        console.log(msg);
    }
});

i want the user to the download the report.

Khenjhie
  • 11
  • 2
  • You said "I cannot download the file instead just saving" also you said "call this file in my url 'Get_summary_excel.php' it will download", please clarify – codemirror Mar 26 '19 at 07:21
  • what im trying to say is, if i press a button that will call the GET_summary_excel.php, it will just save to where my phpfile is located. but if i try to input the actual GET_summary_excel.php to the url without using ajax, it will download to the browser. – Khenjhie Mar 26 '19 at 07:34
  • http://localhost/web%20portal/admin/phpfile/menu (Original URL) http://localhost/web%20portal/admin/phpfile/GET_summary_Excel.php (Will donwload the file) – Khenjhie Mar 26 '19 at 07:36
  • 1
    This will help https://stackoverflow.com/questions/27701981/phpexcel-download-using-ajax-call – codemirror Mar 26 '19 at 07:44
  • You mentioned Ajax in an earlier comment. You can't download files via Ajax. The data becomes a variable in your JavaScript instead of a file on your disk. Instead use a regular HTTP GET request – ADyson Mar 26 '19 at 08:14
  • @ADyson it's not working. – Khenjhie Mar 27 '19 at 01:28
  • Sorry but you will have to be a bit more specific than that about your current problem, and also show your latest code. I can't guess what is happening in code I can't see – ADyson Mar 27 '19 at 06:50

1 Answers1

0

You are not need to create ajax request, just open a new tab to "Get_summary_excel.php" URL and with all of your parameters, than your file will downloaded.

areg_noid
  • 81
  • 4