2

PHPExcel导入表格(带图片)

 1 year ago
source link: https://xushanxiang.com/phpexcel-import-image.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

安装命令:composer require phpoffice/phpexcel 

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

Excel

excel.png

参见《 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.'条数据']);

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK