欢迎阅读「 使用PhpOffice把文件从excel导出到php中 」

使用PhpOffice把文件从excel导出到php中

网站技术 ayflying 2625℃ 评论

有时候需要把excel的数据导入php中,可能是json或者是php变量使用。

PhpOffice的版本已经跟新了不少,整理一下新版可用的方法。


前面需要composer导入库

1
composer require phpoffice/phpspreadsheet


这里直接贴代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use PhpOffice\PhpSpreadsheet\IOFactory;
 
class Excel{
 
public function main($file){
    return $this->getExcel($file);
}
 
/**
 * @param string $file excel文件名
 * @param int $header  头部字段名位置
 * @return array
 * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
 * @author An Yang
 * @time 2021/3/4 10:19
 */
protected function getExcel(string $file, int $header = 2)
{
    //默认参数行数从0开始计算;
    $header -= 1;
 
    $objReader = IOFactory::createReader('Xlsx');   // 有Xls和Xlsx格式两种
    $objPHPExcel $objReader->load($file);  //$file 可以是上传的表格,或者是指定的表格
    // $cells 是包含 Excel 表格数据的数组
    $cells = [];
    foreach ($objPHPExcel->getWorksheetIterator() as $sheelId => $cell) {
        //$cells[] = $cell->toArray();
        $cellName = [];
        foreach ($cell->toArray() as $key => $val) {
 
            //排除标题上面的列
            if ($key $header) {
                continue;
            }
 
            //获取表列字段名
            if ($key == $header) {
                $cellName $val;
                continue;
            }
 
            //字段赋值
            $item = [];
            foreach ($val as $key2 => $val2) {
                $name $cellName[$key2] ?? "";
                if (empty($name)) {
                    continue;
                }
                $cells[$sheelId][$key][$name] = $val2;
            }
        }
    }
    return $cells;
}
 
}


需要使用的excel表大概格式为如下

姓名上午下午
nameampm
张三上班上班
李四迟到上班
王五上班早退


转载请注明:七彩悠悠博客 | 心悠悠 情悠悠 » 使用PhpOffice把文件从excel导出到php中

收藏文章
表情删除后不可恢复,是否删除
取消
确定
图片正在上传,请稍后...
评论内容为空!
还没有评论,快来抢沙发吧!
按钮 内容不能为空!
立刻说两句吧! 查看0条评论

高效,专业,悠悠博客

联系我们