1

I'm developing a small class that will allow you to pass queries and it will create a worksheet for each query.

FYI: This class is still in development and I will be reducing down into smaller functions.

My issue is that for some reason my sheet increment is off and I cant figure out where to put it.

I am calling my class like this:

$ex2 = new ExportToExcel2('Somefile');
$ex2->AddSheet('Sheet1', 'Select * from Division;');
$ex2->AddSheet('Sheet2', 'Select * from Zone');
$ex2->ExportMultiSheet();

I should have two tabs, "Sheet1" and "Sheet2". This is how my sheet ends up looking. All the data is on Sheet1 and Worksheet.

enter image description here

Here is my class:

class ExportToExcel2 {

    public $AllSheetData = [];
    protected $SheetData = [];
    protected $PHPExcel = '';
    protected $FileName = '';

    function __construct($_filename) {
        $this->FileName = $_filename;
        $this->PHPExcel = new PHPExcel;
    }

    public function AddSheet($_WorkSheetName, $_Query) {
        $this->SheetData['Sheet_Name'] = $_WorkSheetName;
        $this->SheetData['Query'] = $_Query;
        $this->AllSheetData[] = $this->SheetData;
        unset($this->SheetData);
    }

    public function ExportMultiSheet() {

        $Result='';
        $count=0;
        $this->PHPExcel->setActiveSheetIndex(0);
        foreach($this->AllSheetData as $subarray)
        {

            foreach($subarray as $key => $value)
            {

                if($count>0)
                {
                    $this->PHPExcel->createSheet($count);
                    $this->PHPExcel->setActiveSheetIndex($count);
                }

                if($key == 'Query') {

                    $Result = dbQuery($value);

                    //set header row
                    $row = 1; // 1-based index
                    $row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC);
                    $col = 0;
                    foreach(array_keys($row_data) as $key) {
                        $this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $key);
                        $col++;
                    }

                    //set body rows
                    $row2 = 2;
                    while($row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC)) {
                        $col2 = 0;

                        foreach($row_data as $key=>$value) {
                            $this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col2, $row2, $value);
                            $col2++;
                        }
                        $row2++;
                    }

                    $count++; 
                }
                if($key =='Sheet_Name')  {
                    $this->PHPExcel->getActiveSheet()->setTitle($value);
                }


                //set all columns to align left
                $this->PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

                //show gridlines?
                $this->PHPExcel->getActiveSheet()->setShowGridlines(true);

                //set columns a through z to auto width
                for($col = 'A'; $col !== 'Z'; $col++) {
                    $this->PHPExcel->getActiveSheet()
                        ->getColumnDimension($col)
                        ->setAutoSize(true);
                }
            }

        }


        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="01simple.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($this->PHPExcel, 'Excel2007');
        $objWriter->save('php://output');

        exit;
    }
}

Any ideas on where to place my $count++?

Solved, Here is the finished class(until its not finished again)

class ExportToExcel2 {

    public $AllSheetData = [];
    protected $SheetData = [];
    protected $PHPExcel  = '';
    protected $FileName  = '';

    function __construct($_filename) {

        $this->FileName = $_filename;
        $this->PHPExcel = new PHPExcel;

        //clean the output buffer before download
        ob_clean();
    }


    public function AddSheet($_WorkSheetName, $_Query) {
        $this->SheetData['Sheet_Name'] = $_WorkSheetName;
        $this->SheetData['Query'] = $_Query;
        $this->AllSheetData[] = $this->SheetData;
        unset($this->SheetData);
    }


    public function ExportMultiSheet($_ExportType='xls') {
        if(!empty($this->AllSheetData)) {
            $count=0;$Result='';
            $this->PHPExcel->setActiveSheetIndex(0);
            foreach($this->AllSheetData as $subarray) {

                if($count>0){
                    $this->PHPExcel->createSheet(null);
                    $this->PHPExcel->setActiveSheetIndex($count);
                }
                $count++; 
                foreach($subarray as $key => $value) {

                    if($key == 'Query') {
                        $Result = dbQuery($value);
                        $this->SetHeaderCells($Result);
                        $this->SetbodyCells($Result);

                    }
                    if($key =='Sheet_Name')  {
                        $this->PHPExcel->getActiveSheet()->setTitle($value);
                    }

                }
            }

            $this->ExportType($_ExportType);
        }
    }


    public function ExportSingleSheet($_Query, $_ExportType='xls') {
        $Result = dbQuery($_Query);
        $this->SetHeaderCells($Result);
        $this->SetBodyCells($Result);
        $this->SetProperties();
        $this->ExportType($_ExportType);
    }


    private function ExportType($_ExportType) {
        if($_ExportType=='xls') {
            $this->DownloadXLS();
        } 
        else if($_ExportType=='csv') {
            $this->DownloadCSV();
        }
    }


    private function SetProperties() {

        //set all columns to align left
        $this->PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

        //show gridlines?
        $this->PHPExcel->getActiveSheet()->setShowGridlines(true);

        //set columns a through z to auto width
        for($col = 'A'; $col !== 'Z'; $col++) {
            $this->PHPExcel->getActiveSheet()
                ->getColumnDimension($col)
                ->setAutoSize(true);
        }

        //set the first sheet to open first
        $this->PHPExcel->setActiveSheetIndex(0);
    }


    private function DownloadXLS() {
        $this->SetProperties();
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$this->FileName.'-'.date("y.m.d").'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($this->PHPExcel, 'Excel2007');
        $objWriter->save('php://output');

        exit;
    }


    private function DownloadCSV() {
        $this->SetProperties();
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment;filename="'.$this->FileName.'-'.date("y.m.d").'.csv"');
        header('Cache-Control: max-age=0');
        $objWriter = new PHPExcel_Writer_CSV($this->PHPExcel);
        $objWriter->save("php://output");

        exit;
    }


    private function SetHeaderCells($Result) {
        $row = 1; // 1-based index
        $row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC);
        $col = 0;
        foreach(array_keys($row_data) as $key) {
            $this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $key);
            $col++;
        }
    }


    private function SetBodyCells($Result) {
        $row2 = 4;
        while($row_data = sqlsrv_fetch_array($Result, SQLSRV_FETCH_ASSOC)) {
            $col2 = 0;

            foreach($row_data as $key=>$value) {
                $this->PHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col2, $row2, $value);
                $col2++;
            }
            $row2++;
        }
    }
}
M H
  • 2,179
  • 25
  • 50

1 Answers1

1

You should first move the sheet generation code from the foreach($subarray loop to your foreach($this->AllSheetData (since you want to add new sheet for every.. well.. new sheet. Not for every new sheet property).

You should then use a very similar code to the one you had, and $counter will be used only within that part of the code. Note that to create a new sheet and place is as the last one, you should simply pass null to the createSheet() method.

So your code should look like this:

public function ExportMultiSheet() {

    ...
    $count = 0;
    foreach($this->AllSheetData as $subarray)
    {
      if ($count > 0)
      {
          $this->PHPExcel->createSheet(null);
          $this->PHPExcel->setActiveSheetIndex($count);
      }
      $count++

      foreach($subarray as $key => $value)
      ...
    }
    ...
uri2x
  • 3,162
  • 1
  • 11
  • 25
  • Thanks man, this got me very close. the issue is that now I am overwriting the first sheet data with the second sheet data and the "Sheet2" is empty. I changed it exactly like you suggested. – M H Sep 12 '15 at 07:07
  • Did you make sure to remove any other reference to `$count`? Here's the code I've used based on your question: http://pastebin.com/EGwKyMGY It'll simply write the `$count` to `A1` cell on each new sheet. See that it's working for you, and then try to figure out the differences from your code. – uri2x Sep 12 '15 at 07:15
  • I had a SetProperties function firing and in there I was setting the activeindex. Working now. i added my finished class above. – M H Sep 12 '15 at 07:56