php读写excel文件
作者:程序员11 时间:2023-02-15 人气:345 QQ交流群\邮箱:1003265987@qq.com
php读写excel文件
要展示的内容
1.引入包
"phpoffice/phpspreadsheet": "1.8.2",
2.读取文件
<?php use PhpOfficePhpSpreadsheetIOFactory; require "vendor/autoload.php"; $f = "/tmp/excelSample.xlsx"; try { $inputFileType = IOFactory::identify($f); $reader = IOFactory::createReader($inputFileType); $spreadSheet = $reader->load($f); //获取第几张数据表,默认从0开始 $sheet = $spreadSheet->getSheet(0); //获取最大行数 $rows = $sheet->getHighestRow(); //获取最大列数 $cols = $sheet->getHighestColumn(); //获取全量数据集,返回数组形式数据 $dataArr = $sheet->rangeToArray('A1:' . $cols . $rows); for ($i = 2; $i <= $rows; $i++) { //获取一列数据 $ret['id'][] = $sheet->getCell('A' . $i)->getValue(); } }catch (Exception $e) { var_dump($e->getMessage()); }
我们把上边的方法改造一下,做个通用的,只需要传入excel文件路径,就可以直接读取文件,返回数组形式的全量数据的方法。
<?php use PhpOfficePhpSpreadsheetIOFactory; require "vendor/autoload.php"; $filepath = "/tmp/excelSample.xlsx"; try { $data = getExcelContents($filepath); var_dump($data); }catch (Exception $e) { var_dump($e->getMessage()); } /** * @throws PhpOfficePhpSpreadsheetException * @throws PhpOfficePhpSpreadsheetReaderException */ function getExcelContents($filepath) { $inputFileType = IOFactory::identify($filepath); $reader = IOFactory::createReader($inputFileType); $spreadSheet = $reader->load($filepath); //获取第几张数据表,默认从0开始 $sheet = $spreadSheet->getSheet(0); //获取最大行数 $rows = $sheet->getHighestRow(); //获取最大列数 $cols = $sheet->getHighestColumn(); //获取全量数据集 $dataArr = $sheet->rangeToArray('A1:' . $cols . $rows); return $dataArr; }
3.写入文件
<?php use PhpOfficePhpSpreadsheetCellDataType; use PhpOfficePhpSpreadsheetIOFactory; use PhpOfficePhpSpreadsheetSpreadsheet; require "vendor/autoload.php"; $filepath = "/tmp/exportExcel.xlsx"; try { $data = [ [ 'id', 'name', 'age' ], [ 1001, 'tomson', 10 ], [ 1009, 'lucifer', 20 ] ]; $spreadSheet = new Spreadsheet(); $sheet = $spreadSheet->getActiveSheet(); $i = 1; foreach ($data as $excel) { $j = 1; if (is_array($excel)) { foreach ($excel as $e) { //强制内容为文本,避免出现科学计数法处理数字的问题 $sheet->setCellValueExplicitByColumnAndRow($j, $i, $e, DataType::TYPE_STRING); $j++; } } $i++; } $writer = IOFactory::createWriter($spreadSheet, 'Xlsx'); $writer->save($filepath); }catch (Exception $e) { var_dump($e->getMessage()); }
看一下写入的excel文件
4.直接返回excel文件
$writer = IOFactory::createWriter($spreadSheet, 'Xlsx'); header("Content-Type: application/vnd.ms-excel"); header("Content-Disposition: attachment;filename=downloadExcel.xlsx"); header("Cache-Control: max-age=0"); $writer->save('php://output');
温馨提示:
欢迎阅读本文章,觉得有用就多来支持一下,没有能帮到您,还有很多文章,希望有一天能帮到您。
- 上一篇:php常用hash加密函数
- 下一篇:apidoc的使用和常见问题的解决办法