PHP怎么生成和读取简单的Excel表格

将数据库读取出来的数据生成对应的表格(无格式):
	因为自己有个需求是需要将数据库的数据生成对应的Excel表格,因为无任何基础,所以在网上花费了大量的时间进行百度,现将自己掌握的内容记录一下,以供后续的带哥们少走弯路,实现简单的需求。
	首先,需要知道存在这么一个插件:https://github.com/PHPOffice/PhpSpreadsheet 这是一个比较常见的用于处理Excel表格的插件。进入你的项目目录,然后在目录中打开命令行输入:
	composer require phpoffice/phpspreadsheet (前提是你已经安装过composer了,具体的方法自行百度)操作之后,就能进行对应的需求开发了。
	
	header('Content-Type: application/octet-stream');
    header('Accept-Ranges:bytes');
    header('Content-Type: application/vnd.ms-excel');
    header('Pragma:no-cache');
    header('Expires:0');
    header('Content-Disposition: attachment; filename='.$messname.'');
    $output = fopen('php://output', 'w') or die("Can't open php://output");
    //UTF8 csv文件头前需添加BOM,不然会是乱码
    fwrite($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
    // 输出标题行
    fputcsv($output, array('用户姓名', '用户电话', '性别','年龄区间','感兴趣的产品','推荐人','信息真实性'));
    //此方法需要将对应的对象数据转化成对应的二维数组进行对应的操作
    $rows = $usersInfos;
    foreach ($rows as $row) {
        fputcsv($output, $row);
    }
    fclose($output) or die("Can't close php://output");
}
这是最简单的可以实现生成Excel表格的方法,并且能将对应的表格通过浏览器下载,具体的通过phpspreadsheet 实现表格的下载可以参照这个:https://www.cnblogs.com/windyet/articles/9711044.html
然后,是读取Excel表格的方法:
 	$file =$_FILES['userinfo'];
    $reader = \PhpOffice\PhpSpreadsheet\IOFactory::load($file['tmp_name']);
    $sheet = $reader->getActiveSheet();
    $res = array();
    foreach ($sheet->getRowIterator(2) as $row){
        $tmp = array();
        foreach ($row->getCellIterator() as $cell){
            $tmp [] = $cell->getFormattedValue();
        }
        $res[$row->getRowIndex()] = $tmp;
    }
    这也是最简单的,通过一个from表格,将表格提交到后台,然后进行最基本的读取。
    具体的API可以参见https://phpspreadsheet.readthedocs.io/en/latest/  进行学习
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章