phpexcel需要创建一个多表Excel,每个工作表都按SQL中的列分组

时间:2019-06-25 18:54:24

标签: excel codeigniter group-by phpexcel

我需要读取数据库表并从中创建一个excel。表中的数据需要按列(村名)进行分组,而excel文件需要以这样的方式存储数据,即每个村庄都有自己的带有相应记录的表。

这是我的CI代码:

$this->db->order_by('sno', 'desc'); 
$this->db->get('tablename');
if($res->num_rows()>0)
{
    $res= $res->result();
}

然后,我使用以下代码创建excel:

require_once $_SERVER['DOCUMENT_ROOT']."/application/views/PHPExcel/Classes/PHPExcel.php";
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle($villagename);
$objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue("A1", "SNO")
            ->setCellValue("B1", "Name")
            ->setCellValue("C1", "Address")
            ->setCellValue("D1", "Mobile");
$i=2;
$rsno=1;
foreach($res AS $r)
{
    $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue("A$i", $rsno)
                ->setCellValue("B$i", $r->name)
                ->setCellValue("C$i", $r->addr)
                ->setCellValueExplicit("D$i", $r->mob, PHPExcel_Cell_DataType::TYPE_STRING);
    $i++;
    $rsno++;
}
$objPHPExcel->setActiveSheetIndex(0);
$sheet = $objPHPExcel->getActiveSheet();
$cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);

foreach ($cellIterator as $cell) {
    $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
}
require_once $_SERVER['DOCUMENT_ROOT']."/application/views/PHPExcel/Classes/PHPExcel/IOFactory.php";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

if (ob_get_contents())
    ob_end_clean();

$objWriter->save('Mydata.xlsx');
header('Content-Disposition: attachment; filename=Mydata.xlsx');
header('Content-Type: application/xlsx');
header('Content-Length: ' . filesize('Mydata.xlsx'));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile('Mydata.xlsx');
return TRUE;

我想使用$this->db->group_by('village');以便获得按村庄分组的结果集,并且需要将Excel文件与村庄和每张纸上的相应数据一起导出。

0 个答案:

没有答案