PHPExcel导入表格(带图片)

作者: xusx 分类: Web 发布时间: 2022-05-10 15:45 浏览:423

PHPExcel 最后一个版本是1.8.1,于2015年发布。该项目于2017年正式弃用,并于2019年永久存档。
该项目已多年未维护,不建议使用于新项目上。 所有用户都必须迁移到其直接继承者 PhpSpreadsheet 或其他替代方案。

安装

安装命令:composer require phpoffice/phpexcel 

或者把下载来的压缩包里面的 Classes 文件夹放入合适的位置。

Excel

上传文件

参见《 Excel导入数据库(php版) 》里的 html 和 js 部分代码。

接收处理

$file_name = $_FILES['upload']['name'];
$tmp_name = $_FILES['upload']['tmp_name'];
require_once($_SERVER['DOCUMENT_ROOT'].'/Classes/PHPExcel.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/Classes/PHPExcel/IOFactory.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/Classes/PHPExcel/Cell.php');
$ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$objPHPExcel = null;

if ($ext === 'xlsx') {
    $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
} elseif ($ext === 'xls') {
    $objReader = \PHPExcel_IOFactory::createReader('Excel5');
}

$objPHPExcel =$objReader->load($tmp_name, $encode = 'utf-8');
if(!$objPHPExcel){
    json(0, ['message'=>'文件读取失败']);
}

$sheet      = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$i          = 0;
$dt         = [];
$data       = [];

// use app\admin\model\content\ContentModel;
$md         = new ContentModel();

$imgData       = array();
$imgDir        = '/uploads/'.date('Ym').'/'.date('d').'/';
$imageFilePath = $_SERVER['DOCUMENT_ROOT'].$imgDir;

if (! file_exists ( $imageFilePath )) {
    mkdir("$imageFilePath", 0777, true);
}

foreach ($sheet->getDrawingCollection() as $key=>$img) {
    list($startColumn, $startRow)= \PHPExcel_Cell::coordinateFromString($img->getCoordinates());
    $imageFileName = $img->getCoordinates() . time();
    $imageFullName = $imageFilePath . $imageFileName . '.' . $img->getExtension();
    $imgData[$startRow] = $imgDir . $imageFileName . '.' . $img->getExtension();
    copy($img->getPath(), $imageFullName);
}

for ($j = 2; $j <= $highestRow; $j++) {
    $data[$i]['uname'] = (string)$objPHPExcel->getActiveSheet()->getCell("A$j")->getValue();
    // ......
    $dt[$i]['ico'] = isset($imgData[$j]) ? $imgData[$j] : '';
    // ......
    if (! ! $id = $md->addContent($dt[$i])) {
        $data[$i]['contentid'] = $id;
        if (! $md->addContentExt($data[$i])) {
            $md->delContent($id);
            json(0, ['message'=>'第'.$i.'条数据导入出错,后续终止']);
            die('');
        }
    } else {
        json(0, ['message'=>'第'.$i.'条数据导入出错,后续终止']);
        die('');
    }
    $i++;
}

json(1, ['message'=>'导入成功'.$i.'条数据']);

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!