ddddd

php读写excel文件

作者:程序员11 时间:2023-02-15 人气:345 QQ交流群\邮箱:1003265987@qq.com
php读写excel文件
要展示的内容

1.引入包

有不少提供读写excel文件的包,这里选择比较常用的一个,加到自己的项目里就好了。

    "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.写入文件

读取的时候,我们能发现读取出来的数据都是数组的形式,那写入excel文件的时候,使用的数据也是数组的形式。

<?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文件

image.png

4.直接返回excel文件

在某些场景下的请求,可能希望直接返回excel文件,这其实也是一种写入,只是写入的目标文件不同。
大部分代码与第3部分类似,只有最后写入的部分略有变化。

	$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');

发现区别了吗?
增加了一些header,然后把输出目标调整了。



温馨提示:

欢迎阅读本文章,觉得有用就多来支持一下,没有能帮到您,还有很多文章,希望有一天能帮到您。

php读写excel文件---相关文章


评论区

ddddd

程序员-学习的网站-想学习编程的码农可以进来看看

首页

视频教程

购物车

我的订单