PhpSpreadsheet + Thinkphp 5.1 导入Excel表格到数据库
安装
composer require phpoffice/phpspreadsheet
引入
use PhpOffice\PhpSpreadsheet\Reader\Xls; use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
获取导入的Excel表格数据
/**
* 获取导入Excel表数据
*
* @param integer $sheet //工作表sheet(传0则获取第一个sheet)
* @param string $file_path // 文件地址
* @param integer $columnCnt //列数(传0则自动获取最大列)
* @param array $options // 操作选项
* @return void
*/
function getImportExcelData($file_path = '', $columnCnt = 0, $sheet = 0, $options = [])
{
// 转码
$file = iconv("utf-8", "gb2312", $file_path);
if (empty($file) or !file_exists($file)) {
throw new \Exception('文件不存在!');
}
$objRead = IOFactory::createReader('Xlsx');
if (!$objRead->canRead($file)) {
/** @var Xls $objRead */
$objRead = IOFactory::createReader('Xls');
if (!$objRead->canRead($file)) {
throw new \Exception('只支持导入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 ($columnCnt === 0) {
/* 取得最大的列号 */
$columnH = $currSheet->getHighestColumn();
/* 兼容原逻辑,循环时使用的是小于等于 */
$columnCnt = Coordinate::columnIndexFromString($columnH);
}
// 获取总行数
$count = $currSheet->getHighestRow();
$data = [];
// 读取内容
for ($i = 2; $i <= $count; $i++) {
$isNull = true;
$m = 0;
for ($n = 1; $n <= $columnCnt; $n++) {
$cellName = Coordinate::stringFromColumnIndex($n);
$cellId = $cellName . $i;
$cell = $currSheet->getCell($cellId);
if (isset($options['format'])) {
/* 获取格式 */
$format = $cell->getStyle()->getNumberFormat()->getFormatCode();
/* 记录格式 */
$options['format'][$i][$cellName] = $format;
}
if (isset($options['formula'])) {
/* 获取公式,公式均为=号开头数据 */
$formula = $currSheet->getCell($cellId)->getValue();
if (0 === strpos($formula, '=')) {
$options['formula'][$cellName . $i] = $formula;
}
}
if (isset($format) && 'm/d/yyyy' == $format) {
/* 日期格式翻转处理 */
$cell->getStyle()->getNumberFormat()->setFormatCode('yyyy/mm/dd');
}
$data[$i][$m] = trim($currSheet->getCell($cellId)->getFormattedValue());
if (!empty($data[$i][$m])) {
$isNull = false;
}
$m++;
}
/* 判断是否整行数据为空,是的话删除该行数据 */
if ($isNull) {
unset($data[$i]);
}
}
return $data;
}

浙公网安备 33010602011771号