导出数据并发送邮件附件Codeigniter

时间:2017-11-09 11:42:40

标签: php codeigniter email export send

我想导出数据并将Excel文件作为附件插入。如何使用codeigniter 2.2.4。

// PHP EXPORT DATA
...
...
$objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="test.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');

// SEND MAIL
$this->load->library('email');
$this->email->from('test@gmail.com', 'Test');
$this->email->to('test@gmail.com', 'Test');
$this->email->subject('EXPORT DATA FILE');
$this->email->message("Test content");
$this->email->attach("INSERT HERE THE EXPORTED FILE");
try {
    $this->email->send();
}
catch(Exception $e) {
    echo $e->getMessage();
}

1 个答案:

答案 0 :(得分:0)

我的控制器:

        public function export() {
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory');
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()->setTitle("title")->setDescription("description");
        // Assign cell values
        $objPHPExcel->setActiveSheetIndex(0);
        // /////////////////////////////////////////////////////
        $wappi_query = 'SELECT * FROM ' . $my_table . '';
        $wappi_list = $this->db->query($wappi_query)->result();
        // /////////////////////////////////////////////////////
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth("10");
        /*Protected Sheet */
        $objPHPExcel->getActiveSheet()->getProtection()->setSheet(false);
        /* File information */
        $objPHPExcel->getProperties()->setCreator("")->setLastModifiedBy("")->setTitle("")->setSubject("")->setDescription("")->setKeywords("")->setCategory("");
        $objPHPExcel->getDefaultStyle()->getFont()->setName('Tahoma')->setSize(10)->setBold(false);
        $objPHPExcel->getActiveSheet()->setCellValue('A1', "ID");
        $objPHPExcel->getActiveSheet()->setCellValue('B1', "UNITY");
        $i = 2;
        foreach ($wappi_list as $data) {
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $i . '', $data->id);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $i . '', $data->unity);
            $i++;
        }
        $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');
        header('Content-type: application/vnd.ms-excel');
        // It will be called file.xls
        header('Content-Disposition: attachment; filename="unity_' . date('d-m-Y') . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter->save('php://output');
}