Home > Backend Development > PHP Tutorial > PHP operates Excel to create Excel and write data

PHP operates Excel to create Excel and write data

WBOY
Release: 2016-07-29 09:12:09
Original
1720 people have browsed it
第一步下载PHPExcel类库 http://phpexcel.codeplex.com/
$dir = str_replace('\\', '/',dirname(__FILE__));
<strong>require</strong>_once $dir.'/PHPExcel.php';

$excelObj = new PHPExcel(); // 相当于在桌面建一个Excel
// 创建三个内置表
for($i =1 ; $i <= 3; $i++){
    if($i > 1){ // 因为默认有一页, 所有从第二开始
        $excelObj->createSheet(); // 创建内置表
    }
    $excelObj->setActiveSheetIndex($i-1); // 从0开始
    $currentSheet = $excelObj->getActiveSheet(); // 获取当前活动sheet
    $currentSheet->setCellValue('A1','父ID')->setCellValue('B1','模型')->setCellValue('C1', '方法')->setCellValue('D1','名称'); // A1表示第一行的第一列 B1表示第一行的第二列,以此类推...
    $data = DB::getData($i); // 这是从数据库读取数据, 每循环一次就取出数据表中 type等于$i的数据 ,写入Excel文件
    $j = 2;
    foreach($data as $val){
        $currentSheet->setCellValue('A'.$j,$val['parentid'])->setCellValue('B'.$j,$val['model'])->setCellValue('C'.$j, $val['action'])->setCellValue('D'.$j,$val['name']);
        $j++; // 每循环一次换一行写入数据
    }
}

// 下面两行代码是写入Excel文件
$sheeetWrite = PHPExcel_IOFactory::createWriter($excelObj, 'Excel2007'); 
$sheeetWrite->save($dir.'/testExcel.xlsx');
Copy after login

以上就介绍了PHP操作Excel 创建Excel并写入数据,包括了require方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template