phpExcel导出

来源:互联网 发布:淘宝 产品对比 违规 编辑:程序博客网 时间:2024/05/19 13:29

本文转自http://www.phpernote.com/php-function/365.html

首先从github上面下载到类库并将PHPExcel.php引入到自己的项目当中

$data=array(
06    0=>array(
07        'id'=>1001,
08        'username'=>'张飞',
09        'password'=>'123456',
10        'address'=>'三国时高老庄250巷101室'
11    ),
12    1=>array(
13        'id'=>1002,
14        'username'=>'关羽',
15        'password'=>'123456',
16        'address'=>'三国时花果山'
17    ),
18    2=>array(
19        'id'=>1003,
20        'username'=>'曹操',
21        'password'=>'123456',
22        'address'=>'延安西路2055弄3号'
23    ),
24    3=>array(
25        'id'=>1004,
26        'username'=>'刘备',
27        'password'=>'654321',
28        'address'=>'愚园路188号3309室'
29    )
30);
31$objPHPExcel=new PHPExcel();
32$objPHPExcel->getProperties()->setCreator('http://www.phpernote.com')
33                             ->setLastModifiedBy('http://www.phpernote.com')
34                             ->setTitle('Office 2007 XLSX Document')
35                             ->setSubject('Office 2007 XLSX Document')
36                             ->setDescription('Document for Office 2007 XLSX, generated using PHP classes.')
37                             ->setKeywords('office 2007 openxml php')
38                             ->setCategory('Result file');
39$objPHPExcel->setActiveSheetIndex(0)
40            ->setCellValue('A1','ID')
41            ->setCellValue('B1','用户名')
42            ->setCellValue('C1','密码')
43            ->setCellValue('D1','地址');
44             
45$i=2;          
46foreach($data as $k=>$v){
47    $objPHPExcel->setActiveSheetIndex(0)
48            ->setCellValue('A'.$i,$v['id'])
49            ->setCellValue('B'.$i,$v['username'])
50            ->setCellValue('C'.$i,$v['password'])
51            ->setCellValue('D'.$i,$v['address']);
52    $i++;
53}
54$objPHPExcel->getActiveSheet()->setTitle('三年级2班');
55$objPHPExcel->setActiveSheetIndex(0);
56$filename=urlencode('学生信息统计表').'_'.date('Y-m-dHis');
57 
58//生成xlsx文件
59/*
60header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
61header('Content-Disposition: attachment;filename="'.$filename.'.xlsx"');
62header('Cache-Control: max-age=0');
63$objWriter=PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
64*/
65 
66//生成xls文件
67header('Content-Type: application/vnd.ms-excel');
68header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
69header('Cache-Control: max-age=0');
70$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel'Excel5');
71 
72$objWriter->save('php://output');
73exit;