简体   繁体   中英

PHPExcel: Using a MySQLi query on '01simple-download-xls.php' example

Would anyone know of a good working example of someone taking the "01simple-download-xls.php" of PHPExcel and modifying it to work with a MySQLi query? I've been having some trouble finding a good working example.

I'd like to leave everything in the example intact and just replace this one section of code (below) with a MySQLi query.

It looks like I could just loop through the query and dump the setCellValue (I think). I've been trying to find a more elegant solution where (without knowing the number of columns involved) the code could work for any query without modifications.

So, I'd like to just replace this one piece of the example:

// Add some data
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Hello')
            ->setCellValue('B2', 'world!')
            ->setCellValue('C1', 'Hello')
            ->setCellValue('D2', 'world!');

// Miscellaneous glyphs, UTF-8
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A4', 'Miscellaneous glyphs')
            ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');

This is the full example file included in the PHPExcel samples (01simple-download-xls.php):

<?php
/**
 * PHPExcel
 *
 * Copyright (c) 2006 - 2015 PHPExcel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category   PHPExcel
 * @package    PHPExcel
 * @copyright  Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
 * @version    ##VERSION##, ##DATE##
 */

/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');

if (PHP_SAPI == 'cli')
    die('This example should only be run from a Web Browser');

/** Include PHPExcel */
require_once dirname(__FILE__) . '/../Classes/PHPExcel.php';


// Create new PHPExcel object
$objPHPExcel = new PHPExcel();

// Set document properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                             ->setLastModifiedBy("Maarten Balliauw")
                             ->setTitle("Office 2007 XLSX Test Document")
                             ->setSubject("Office 2007 XLSX Test Document")
                             ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                             ->setKeywords("office 2007 openxml php")
                             ->setCategory("Test result file");


// Add some data
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Hello')
            ->setCellValue('B2', 'world!')
            ->setCellValue('C1', 'Hello')
            ->setCellValue('D2', 'world!');

// Miscellaneous glyphs, UTF-8
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A4', 'Miscellaneous glyphs')
            ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');

// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Simple');


// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);


// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="01simple.xls"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;

Download PHPExcel here and try the below code.

$sql = mysqli_query($conn, "SELECT id FROM invoice_product WHERE model_name = '$mname' && model_no = '$mno' ORDER BY color");
$a=0;
while ($result = mysqli_fetch_array($sql))
{
    $id_array[$a] = $result[id];
    $a++;
}

$sql2 = mysqli_query($conn, "SELECT * FROM invoice_imei WHERE invoice_product_id IN (".implode(',',$id_array).")");

$setExcelName = "IMEI"; 

require_once '../PHPExcel/Classes/PHPExcel/IOFactory.php';
require_once '../PHPExcel/Classes/PHPExcel.php';

// Create new PHPExcel object
$objPHPExcel = new PHPExcel(); 

//setting column heading
$objPHPExcel->getActiveSheet()->setCellValue('A1',"Model Name"); 
$objPHPExcel->getActiveSheet()->setCellValue('B1',"Model No."); 
$objPHPExcel->getActiveSheet()->setCellValue('C1',"Color"); 
$objPHPExcel->getActiveSheet()->setCellValue('D1',"IMEI"); 
$objPHPExcel->getActiveSheet()->setCellValue('E1',"Status"); 

//setting column body
$i=2; //starting from row 2 bcz row 1 set to header
while ($result2 = mysqli_fetch_array($sql2)) {
    $sql3 = mysqli_query($conn, "SELECT color FROM invoice_product WHERE id = '$result2[invoice_product_id]'"); 
    $result3 = mysqli_fetch_assoc($sql3);

    $objPHPExcel->getActiveSheet()->setCellValue('A'.$i,$mname);
    $objPHPExcel->getActiveSheet()->setCellValue('B'.$i,$mno);
    $objPHPExcel->getActiveSheet()->setCellValue('C'.$i,$result3[color]);
    $objPHPExcel->getActiveSheet()->setCellValue('D'.$i,$result2[imei]);
    if ($result2[status] == 0) { 
        $objPHPExcel->getActiveSheet()->setCellValue('E'.$i,'Not Used');
    } else {
        $objPHPExcel->getActiveSheet()->setCellValue('E'.$i,'Used');
    }
    $i++;
}
// Redirect output to a client’s web browser (Excel5)
header('Content-type: application/xlsx');
header('Content-Disposition: attachment;filename="IMEI.xls"');
header('Cache-Control: max-age=0');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

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

You can take advantage of the worksheet's fromArray() method to set a row of cells from an array as a single call, which will work regardless of how many values there are in the array:

$row=2;
while ($result = mysqli_fetch_row($queryResultSet)) {
    $objPHPExcel->getActiveSheet()
        ->fromArray($result, null, 'A'.$row++);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM