使用phpExcel将数据批量导出

if(isset($_POST['export']) && $_POST['export'] == '导出所选数据')
{
    //此处为多选框已勾选的数据
    $export_id=$_POST['choose'];
    if($export_id !='')
    {
        $str = implode(",", $export_id);
        $sql = "SELECT * from page WHERE ID in($str)";
        $result = mysqli_query($link, $sql);
        if ($result)
        {
            while ($row = mysqli_fetch_assoc($result))
            {
                $page_info[] = $row;
            }
        }

    
        /** 引入PHPExcel */
        include("../Classes/PHPExcel.php");
        include("../Classes/PHPExcel/Writer/Excel2007.php");

        // 创建Excel文件对象
        $objPHPExcel = new PHPExcel();
        // 文档信息,点击表格鼠标右键查看属性可以看到
        $objPHPExcel->getProperties()->setCreator("Paper Database Center")
            ->setLastModifiedBy("Excel Document")
            ->setTitle("Excel Document")
            ->setSubject("Excel Document")
            ->setDescription("Excel Document from Paper Database Center")
            ->setKeywords("Excel openxml php")
            ->setCategory("Excel export result file");

        //根据excel坐标,添加数据
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '序号')
            ->setCellValue('B1', '标题')
            ->setCellValue('C1', '作者');

        //添加表格内容
        foreach ($page_info as $k => $v) {
            $num = $k + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $num, ++$k)
                ->setCellValue('B' . $num, $v['title'])
                ->setCellValue('C' . $num, $v['author']);

        }

        // 重命名工作sheet
        $objPHPExcel->getActiveSheet()->setTitle('export data');

        // 设置第一个sheet为工作的sheet
        $objPHPExcel->setActiveSheetIndex(0);

        // 保存Excel 95格式文件,,保存路径为当前路径,
        //$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        // $objWriter->save('export.xls');

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition:attachment;filename="export.xls"');
        //header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

    }
    else
    {
        echo "<script>alert('未选中任何数据,请重新选择!');history.go(-1);</script>";
    }
}   

 

posted @ 2017-09-30 22:09  Vine.Y  阅读(644)  评论(0编辑  收藏  举报
TOP