PhpSpreadsheet用法 - xiaogardenz/Work GitHub Wiki

composer require phpoffice/phpspreadsheet

下载前如果慢的话,可以切换国外的镜像,在composer.json添加

"repositories": {
        "packagist": {
            "type": "composer",
            "url": "https://packagist.phpcomposer.com"
        }
    }

导入用法:

1、先引入相关文件

require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
/**
 * 使用PHPEXECL导入
 *
 * @param string $file      文件地址
 * @param int    $type      类型:csv,xls,xlsx
 * @param int    $sheet     工作表sheet(传0则获取第一个sheet)
 * @param int    $line      从第几行开始
 * @param int    $columnCnt 列数(传0则自动获取最大列)
 * @param array  $options   操作选项
 *                          array mergeCells 合并单元格数组
 *                          array formula    公式数组
 *                          array format     单元格格式数组
 *
 * @return array
 * @throws Exception
 */

function importExecl(string $file = '', string $type = '' , int $sheet = 0, int $line = 1, int $columnCnt = 0, &$options = [])
{
	try {
		if (empty($file) OR !file_exists($file)) {
			jsonError('文件不存在!');
		}

		$objRead = IOFactory::createReader($type);

		if ( $type == 'Csv' ) {
			$objRead
				->setDelimiter(',')
				->setInputEncoding('GBK')
				->setEnclosure('"')
				->setSheetIndex(0);
		}


		if (!$objRead->canRead($file)) {

			jsonError('只支持导入Excel文件!');

		}

		/* 如果不需要获取特殊操作,则只读内容,可以大幅度提升读取Excel效率 */
		empty($options) && $objRead->setReadDataOnly(true);

		/* 建立excel对象 */
		$obj = $objRead->load($file);

		/* 获取指定的sheet表 */
		$currSheet = $obj->getSheet($sheet);

		if (isset($options['mergeCells'])) {
			/* 读取合并行列 */
			$options['mergeCells'] = $currSheet->getMergeCells();
		}

		if (0 == $columnCnt) {
			/* 取得最大的列号 */
			$columnH = $currSheet->getHighestColumn();
			/* 兼容原逻辑,循环时使用的是小于等于 */
			$columnCnt = Coordinate::columnIndexFromString($columnH);
		}

		/* 获取总行数 */
		$rowCnt = $currSheet->getHighestRow();
		$data   = [];

		/* 读取内容 */
		for ($_row = $line; $_row <= $rowCnt; $_row++) {
			$isNull = true;

			for ($_column = 1; $_column <= $columnCnt; $_column++) {
				$cellName = Coordinate::stringFromColumnIndex($_column);
				$cellId   = $cellName . $_row;
				$cell     = $currSheet->getCell($cellId);

				if (isset($options['format'])) {
					/* 获取格式 */
					$format = $cell->getStyle()->getNumberFormat()->getFormatCode();
					/* 记录格式 */
					$options['format'][$_row][$cellName] = $format;
				}

				if (isset($options['formula'])) {
					/* 获取公式,公式均为=号开头数据 */
					$formula = $currSheet->getCell($cellId)->getValue();

					if (0 === strpos($formula, '=')) {
						$options['formula'][$cellName . $_row] = $formula;
					}
				}

				if (isset($format) && 'm/d/yyyy' == $format) {
					/* 日期格式翻转处理 */
					$cell->getStyle()->getNumberFormat()->setFormatCode('yyyy/mm/dd');
				}

				$data[$_row][$cellName] = trim($currSheet->getCell($cellId)->getFormattedValue());

				if (!empty($data[$_row][$cellName])) {
					$isNull = false;
				}
				if ( count($data[$_row]) == $columnCnt ) {
					yield [
						'total' => $rowCnt - $line + 1,
						'data'  => $data[$_row]
					];
				}

			}

			/* 判断是否整行数据为空,是的话删除该行数据 */
			if ($isNull) {
				unset($data[$_row]);
			}

		}

		return $data;
	} catch (\PhpOffice\PhpSpreadsheet\Exception $e) {
		jsonError($e->getMessage());
	}
}