Prasad Patel
Prasad Patel

Reputation: 747

Export to Excel/CSV with multiple tabs in php?

Our application needs an export to Excel sheet which has multiple tabs(excel sheet). For this Am using [PHPExcel][1] but it is working fine but how to insert data dynamically form mysql database.

Below is my code:

<?php
require_once 'PHPExcel.php';
require_once 'PHPExcel/IOFactory.php';

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

// Create a first sheet, representing sales data
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'Something');

// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle('Name of Sheet 1');

// Create a new worksheet, after the default sheet 
$objPHPExcel->createSheet();

// Add some data to the second sheet, resembling some different data types
$objPHPExcel->setActiveSheetIndex(1);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'More data');

// Rename 2nd sheet
$objPHPExcel->getActiveSheet()->setTitle('Second sheet');

// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="name_of_file.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

It is working fine, Excel sheet is getting generated but how to add data from the database along with Excel sheet column names with that of table column names. In place of "$objPHPExcel->getActiveSheet()->setCellValue('A1', 'More data');" how to add table data dynamically?

Upvotes: 0

Views: 3203

Answers (1)

affaz
affaz

Reputation: 1191

Assign the data from db into array using select query and fill the data to excel using fromArray

    $data=[];
    $i=2;
    $mx=mysqli_query($con,"SELECT * FROM table");
                  while($row=mysqli_fetch_array($mx))
                  {
                      //values from db..col A,col B,col C,col D
                    $data= array($row[0],$row[1],$row[2],$row[3]);

                 //row number                 
                   $ii="A".$i;

        //insert data from db to excel 
                    $objPHPExcel->getActiveSheet()->fromArray($data, ' ', $ii);
                     $i++;

                  }

Upvotes: 0

Related Questions