懵逼树上懵逼果
懵逼树下你和我

phpexcel导出实例

public function exportExcel($data)
{
    $name = $data['name'];      // 文件名
    $title = $data['title'];    // 标题
    $head = $data['head'];      // 表头信息
    $list = $data['list'];      // 列表
    
    $letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    $filename = $name . '.xls';
    header('Pragma:public');
    header('Content-Type:application/x-msexecl;name="' . $filename . '"');
    header('Content-Disposition:inline;filename="' . $filename . '"');

    // 实例化phpexcel
    $obj_excel = new \PHPExcel();
    
    // 写入表头信息
    for ($i = 0; $i < count($head); $i++)
    {
        $obj_excel->setActiveSheetIndex(0)->setCellValue($letters[$i] . '1', $head[$i]);
    }

    // 写入列表数据
    foreach ($list as $key => $item)
    {
        $key2 = 0;
        foreach ($item as $tem)
        {
            $obj_excel->setActiveSheetIndex(0)->setCellValue($letters[$key2] . ($key + 2), $tem);
            $key2++;
        }
    }

    // 写入标题
    $obj_excel->getActiveSheet()->setTitle($title);

    // 处理宽度
    foreach ($obj_excel->getWorksheetIterator() as $worksheet)
    {
        $obj_excel->setActiveSheetIndex($obj_excel->getIndex($worksheet));
        $sheet = $obj_excel->getActiveSheet();
        $cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(true);
        foreach ($cellIterator as $cell)
        {
            $sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
        }
    }

    $objWriter = \PHPExcel_IOFactory::createWriter($obj_excel, 'Excel5');
    $objWriter->save( 'php://output');
}
赞(0)
未经允许不得转载:astipsy » phpexcel导出实例
分享到: 更多 (0)