如何使用php Excel在excel电子表格中插入数据

时间:2017-07-06 10:38:46

标签: php excel insert phpexcel

如何使用phpExcel在Excel电子表格中插入数据?

请帮帮我。

1 个答案:

答案 0 :(得分:0)

这假设所有库都已加载并导入页面

function report($result){
//result is the data to be filled


    $ea = new \PHPExcel();
    $ea->getProperties()
        ->setCreator('YOURNAME')
        ->setTitle('PHPExcel');

    $ews = $ea->getSheet(0);

    $ews->setCellValue('a1', 'ID'); // Sets cell 'a1' to value 'ID
    $ews->setCellValue('b1', 'first Name');
    $ews->setCellValue('c1', 'Last Name');



//this is to set header colour
    $header = 'a1:c1';
    $ews->getStyle($header)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('0000ffe6');
    $style = array(
        'font' => array('bold' => true,),
        'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,),
    );
    $ews->getStyle($header)->applyFromArray($style);

    $ews->fromArray($result, '-', 'A2');


//this is to autosize columns to fit data
    for ($col = ord('a'); $col <= ord('c'); $col++)
    {
        $ews->getColumnDimension(chr($col))->setAutoSize(true);
    }


// Redirect output to a clients web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="report.xlsx"');
    header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
//
//// If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0

    $objWriter = PHPExcel_IOFactory::createWriter($ea, 'Excel2007');
    $objWriter->save('php://output');
    exit;

}