PHPExcel多表循环问题

时间:2015-09-12 04:56:03

标签: php excel phpexcel

我正在开发一个允许您传递查询的小类,它将为每个查询创建一个工作表。

仅供参考:这个课程仍处于开发阶段,我将缩减为更小的功能。

我的问题是,由于某些原因,我的表单增量已关闭,我无法确定将其放在何处。

我这样称呼我的班级:

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

我应该有两个标签,“Sheet1”和“Sheet2”。这就是我的表格最终看起来的样子。所有数据都在Sheet1和工作表上。

enter image description here

这是我的班级:

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;
    }
}

关于在哪里放置$ count ++的任何想法?

解决了,这是完成的课程(直到它没有再完成)

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++;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您应首先将工作表生成代码从foreach($subarray循环移动到foreach($this->AllSheetData(因为您要为每个.. well ..新工作表添加新工作表。不适用于每个新工作表属性)。

然后,您应该使用与您拥有的代码非常相似的代码,并且$counter将仅在代码的该部分中使用。请注意,要创建新工作表和地点是最后一个,您只需将null传递给createSheet()方法。

所以你的代码应该是这样的:

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)
      ...
    }
    ...