早睡早起,方能养生
Sleep early rise early, way to keep healthy

PHP读取xls表格数据

super
2023-12-12 18:00
views 423

PHP读取xls表格:

 

把一些bug改了,现在7.4版本能直接使用

 

phpexcel1.8下载

 

 

<?php

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

function to_num_str($str)
{
    $char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $char = str_split($char);

    if (is_numeric($str)) {
        $one = floor($str / 26);
        --$one;
        $two = $str % 26;
        return isset($char[$one]) ? $char[$one] : '' . $char[$two];
    } else {
        $str = str_split($str);
        if (!isset($str[1])) {
            $one = $str[0] ? array_flip($char)[$str[0]] : -1;
            return $one;
        } else {
            $one = $str[0] ? array_flip($char)[$str[0]] : -1;
            $two = $str[1] ? array_flip($char)[$str[1]] : -1;
            return ($one + 1) * 26 + $two;
        }
    }
}

function getXlsData($filename, $returnTitle = false)
{

    if (!file_exists($filename)) {
        return [];
    }

    /** Include PHPExcel_IOFactory */
    require_once dirname(__FILE__) . '\phpexcel1.8\PHPExcel\IOFactory.php';

    /** 读取指定的 Excel 文件  **/
    $excel = PHPExcel_IOFactory::load($filename);

    /** 获取第一个工作表(Worksheet)**/
    $sheet = $excel->getActiveSheet();

    /** 获取行数和列数 **/
    $maxColumn = to_num_str($sheet->getHighestColumn()); // 最大列数
    $maxRow    = $sheet->getHighestRow();                // 最大行数

    $data = [];

    /** 读取每行数据 **/
    $firstRow = $returnTitle ? 1 : 2;
    for ($row = $firstRow; $row <= $maxRow; $row++) {
        for ($col = 1; $col <= $maxColumn; $col++) {
            $data[$row - 1][] = $sheet->getCell(to_num_str($col) . $row)->getValue();
        }
    }
    return $data;
}

// 使用
$data = getXlsData('./data.xls', true);

print_r($data);

 



分享
0 条讨论
top