PhpOffice获取写入excel中图片的方法

      发布在:后端技术      评论:0 条评论

具体上代码:


//    导入
   public function import(){
$file = $this->request->request('file');
if (!$file) {
$this->error(__('Parameter %s can not be empty', 'file'));
}
$filePath = ROOT_PATH . DS . 'public' . DS . $file;
if (!is_file($filePath)) {
$this->error(__('No results were found'));
}
//实例化reader
       $ext = pathinfo($filePath, PATHINFO_EXTENSION);
if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
$this->error(__('Unknown data format'));
}
if ($ext === 'csv') {
$file = fopen($filePath, 'r');
$filePath = tempnam(sys_get_temp_dir(), 'import_csv');
$fp = fopen($filePath, "w");
$n = 0;
while ($line = fgets($file)) {
$line = rtrim($line, "\n\r\0");
$encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
if ($encoding != 'utf-8') {
$line = mb_convert_encoding($line, 'utf-8', $encoding);
}
if ($n == 0 || preg_match('/^".*"$/', $line)) {
fwrite($fp, $line . "\n");
} else {
fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
}
$n++;
}
fclose($file) || fclose($fp);

$reader = new Csv();
} elseif ($ext === 'xls') {
$reader = new Xls();
} else {
$reader = new Xlsx();
}

//导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
       $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

$table = $this->model->getQuery()->getTable();
$database = \think\Config::get('database.database');
$fieldArr = [];
$list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
foreach ($list as $k => $v) {
if ($importHeadType == 'comment') {
$fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
} else {
$fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
}
}

//加载文件
       $insert = [];
try {
if (!$PHPExcel = $reader->load($filePath)) {
$this->error(__('Unknown data format'));
}
$currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
           $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
           $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
           $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
$fields = [];

for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
$fields[] = $val;
}
}

for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
$values = [];
for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
if($fields[$currentColumn-1]=='头像'){
//                        调用头像获取方法
                       $val=$this->writeImageInCell($currentSheet,Coordinate::stringFromColumnIndex(((int) $currentColumn) ). $currentRow);
}else{
$val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
}


$values[] = is_null($val) ? '' : trim($val);
}
$row = [];
$temp = array_combine($fields, $values);
foreach ($temp as $k => $v) {
if (isset($fieldArr[$k]) && $k !== '') {
$v=trim($v);
if($fieldArr[$k]=='pxtime')$v=strtotime($v);
if($fieldArr[$k]=='id' && $v=='')continue;
$row[$fieldArr[$k]] = $v;
}
}

$row=array_filter($row);
if (!empty($row)) {
//                    3、证书导入自动生成证书编号(生成规则:培训日期+身份证后六位数)
                   if(empty($row['zsbh'])){
$row['zsbh']=date('Ymd',$row['pxtime']).substr($row['sfzh'],-6);
}
$insert[] = $row;
}
}
} catch (Exception $exception) {
$this->error($exception->getMessage());
}
if (!$insert) {
$this->error(__('No rows were updated'));
}

try {
//是否包含admin_id字段
           $has_admin_id = false;
foreach ($fieldArr as $name => $key) {
if ($key == 'admin_id') {
$has_admin_id = true;
break;
}
}
if ($has_admin_id) {
$auth = Auth::instance();
foreach ($insert as &$val) {
if (!isset($val['admin_id']) || empty($val['admin_id'])) {
$val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
}
}
}

$this->model->saveAll($insert);
} catch (PDOException $exception) {
$msg = $exception->getMessage();
if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
$msg = "导入失败,包含【{$matches[1]}】的记录已存在";
};
           $this->error($msg);
} catch (\Exception $e) {
$this->error($e->getMessage());
}

$this->success();
}
//导出
   public function export()
{
if ($this->request->isPost()) {
set_time_limit(0);
$search = $this->request->post('search');
$ids = $this->request->post('ids');
$filter = $this->request->post('filter');
$op = $this->request->post('op');
$columns = $this->request->post('columns');

$spreadsheet = new Spreadsheet();

$spreadsheet->getProperties()
->setCreator("FastAdmin")
->setLastModifiedBy("FastAdmin")
->setTitle("标题")
->setSubject("Subject");
$spreadsheet->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
$spreadsheet->getDefaultStyle()->getFont()->setSize(13);
$spreadsheet->getDefaultStyle()->getFont()->setBold(true);

$worksheet = $spreadsheet->setActiveSheetIndex(0);
$whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]];
$this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
list($where, $sort, $order, $offset, $limit) = $this->buildparams();

$line = 1;
$list = [];
$this->model
               ->field($columns)
->where($where)
->where($whereIds)
->chunk(100, function ($items) use (&$list, &$line, &$worksheet,&$spreadsheet) {
$styleArray = [ 'font' => [ 'bold'  => false,
'color' => ['rgb' => '000000'],
'size'  => 12,
'name'  => 'Microsoft Yahei'],'alignment' => [
//                        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                       'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
]];
$list = $items = collection($items)->toArray();
$first = array_keys($list[0]);
foreach ($first as $index => $item) {
$worksheet->setCellValueByColumnAndRow($index+1, 1, __($item));
}
foreach ($items as $index => $item) {
$line++;
$col = 1;
foreach ($item as $field => $value) {
if($field=='pxtime'){
$value=date('Y-m-d H:i:s');
}elseif($field=='photo'){
//                                头像
                               $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('头像');
$drawing->setDescription('头像');
if(strpos($value,'/')===0){
$fileImg=ROOT_PATH.'public'.$value;
}else{
$fileImg=$value;
}
if(!file_exists($fileImg)){
//                                    var_dump($fileImg);exit();
                                   $col++;
continue;
}
$drawing->setPath($fileImg);
$drawing->setWidth(80);
$drawing->setHeight(80);
//                              $objDrawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $oneCellAnchor->from->col) + 1) . ($oneCellAnchor->from->row + 1));
                               $spreadsheet->getActiveSheet()->getRowDimension($line)->setRowHeight(80);
$drawing->setCoordinates(Coordinate::stringFromColumnIndex(((int) $col) ). $line);
$drawing->setOffsetX(0);
$drawing->setOffsetY(0);
$drawing->setWorksheet($spreadsheet->getActiveSheet());
$col++;
continue;
}
$worksheet->setCellValueByColumnAndRow($col, $line, " ".$value);
$worksheet->getStyleByColumnAndRow($col, $line)->getNumberFormat()->setFormatCode('@');
$worksheet->getCellByColumnAndRow($col, $line)->getStyle()->applyFromArray($styleArray);

$col++;
}
}

});


// Redirect output to a client’s web browser (Excel2007)
           $title = date("YmdHis");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
           header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
           header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
           header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
           header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
           header('Pragma: public'); // HTTP/1.0


           $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
return;
       }
}

/**
获取单元内图片方法
    */
   private function writeImageInCell(Worksheet $pSheet, $coordinates)
{
// Construct HTML
       $val = '';

// Write images
       foreach ($pSheet->getDrawingCollection() as $drawing) {
if ($drawing instanceof Drawing) {
if ($drawing->getCoordinates() == $coordinates) {
//                    zip:///www/wwwroot/picdemo.szfeirunda.com/public/uploads/20220922/680ee1cc59244a9d3dc143f9192edbed.xlsx#xl/media/c22977ac13dac76be1a1f13fb2b843a41.png
                   if ($drawing->getPath()) {
// Check if the source is a URL or a file path
                       if ($drawing->getIsURL()) {
$imageContents = file_get_contents($drawing->getPath());
$filePath = tempnam(sys_get_temp_dir(), 'Drawing');
file_put_contents($filePath , $imageContents);
$mimeType = mime_content_type($filePath);
// You could use the below to find the extension from mime type.
                           // https://gist.github.com/alexcorvi/df8faecb59e86bee93411f6a7967df2c#gistcomment-2722664
                           $extension = mime2ext($mimeType);
unlink($filePath);
} else {
$zipReader = fopen($drawing->getPath(),'r');
$imageContents = '';
while (!feof($zipReader)) {
$imageContents .= fread($zipReader,1024);
}
fclose($zipReader);
$extension = $drawing->getExtension();
}
if(!is_dir(ROOT_PATH.'public/uploads/'.date('Ymd'))){
mkdir(ROOT_PATH.'public/uploads/'.date('Ymd'),755,true);
}
$val='/uploads/'.date('Ymd').'/'.md5($imageContents).'.'.$extension;
file_put_contents(ROOT_PATH.'public'.$val,$imageContents);
}

}
}
}

return $val;
}

另外使用到的一个函数:

function mime2ext($mime) {
$mime_map = [
'video/3gpp2'                                                               => '3g2',
'video/3gp'                                                                 => '3gp',
'video/3gpp'                                                                => '3gp',
'application/x-compressed'                                                  => '7zip',
'audio/x-acc'                                                               => 'aac',
'audio/ac3'                                                                 => 'ac3',
'application/postscript'                                                    => 'ai',
'audio/x-aiff'                                                              => 'aif',
'audio/aiff'                                                                => 'aif',
'audio/x-au'                                                                => 'au',
'video/x-msvideo'                                                           => 'avi',
'video/msvideo'                                                             => 'avi',
'video/avi'                                                                 => 'avi',
'application/x-troff-msvideo'                                               => 'avi',
'application/macbinary'                                                     => 'bin',
'application/mac-binary'                                                    => 'bin',
'application/x-binary'                                                      => 'bin',
'application/x-macbinary'                                                   => 'bin',
'image/bmp'                                                                 => 'bmp',
'image/x-bmp'                                                               => 'bmp',
'image/x-bitmap'                                                            => 'bmp',
'image/x-xbitmap'                                                           => 'bmp',
'image/x-win-bitmap'                                                        => 'bmp',
'image/x-windows-bmp'                                                       => 'bmp',
'image/ms-bmp'                                                              => 'bmp',
'image/x-ms-bmp'                                                            => 'bmp',
'application/bmp'                                                           => 'bmp',
'application/x-bmp'                                                         => 'bmp',
'application/x-win-bitmap'                                                  => 'bmp',
'application/cdr'                                                           => 'cdr',
'application/coreldraw'                                                     => 'cdr',
'application/x-cdr'                                                         => 'cdr',
'application/x-coreldraw'                                                   => 'cdr',
'image/cdr'                                                                 => 'cdr',
'image/x-cdr'                                                               => 'cdr',
'zz-application/zz-winassoc-cdr'                                            => 'cdr',
'application/mac-compactpro'                                                => 'cpt',
'application/pkix-crl'                                                      => 'crl',
'application/pkcs-crl'                                                      => 'crl',
'application/x-x509-ca-cert'                                                => 'crt',
'application/pkix-cert'                                                     => 'crt',
'text/css'                                                                  => 'css',
'text/x-comma-separated-values'                                             => 'csv',
'text/comma-separated-values'                                               => 'csv',
'application/vnd.msexcel'                                                   => 'csv',
'application/x-director'                                                    => 'dcr',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'   => 'docx',
'application/x-dvi'                                                         => 'dvi',
'message/rfc822'                                                            => 'eml',
'application/x-msdownload'                                                  => 'exe',
'video/x-f4v'                                                               => 'f4v',
'audio/x-flac'                                                              => 'flac',
'video/x-flv'                                                               => 'flv',
'image/gif'                                                                 => 'gif',
'application/gpg-keys'                                                      => 'gpg',
'application/x-gtar'                                                        => 'gtar',
'application/x-gzip'                                                        => 'gzip',
'application/mac-binhex40'                                                  => 'hqx',
'application/mac-binhex'                                                    => 'hqx',
'application/x-binhex40'                                                    => 'hqx',
'application/x-mac-binhex40'                                                => 'hqx',
'text/html'                                                                 => 'html',
'image/x-icon'                                                              => 'ico',
'image/x-ico'                                                               => 'ico',
'image/vnd.microsoft.icon'                                                  => 'ico',
'text/calendar'                                                             => 'ics',
'application/java-archive'                                                  => 'jar',
'application/x-java-application'                                            => 'jar',
'application/x-jar'                                                         => 'jar',
'image/jp2'                                                                 => 'jp2',
'video/mj2'                                                                 => 'jp2',
'image/jpx'                                                                 => 'jp2',
'image/jpm'                                                                 => 'jp2',
'image/jpeg'                                                                => 'jpeg',
'image/pjpeg'                                                               => 'jpeg',
'application/x-javascript'                                                  => 'js',
'application/json'                                                          => 'json',
'text/json'                                                                 => 'json',
'application/vnd.google-earth.kml+xml'                                      => 'kml',
'application/vnd.google-earth.kmz'                                          => 'kmz',
'text/x-log'                                                                => 'log',
'audio/x-m4a'                                                               => 'm4a',
'application/vnd.mpegurl'                                                   => 'm4u',
'audio/midi'                                                                => 'mid',
'application/vnd.mif'                                                       => 'mif',
'video/quicktime'                                                           => 'mov',
'video/x-sgi-movie'                                                         => 'movie',
'audio/mpeg'                                                                => 'mp3',
'audio/mpg'                                                                 => 'mp3',
'audio/mpeg3'                                                               => 'mp3',
'audio/mp3'                                                                 => 'mp3',
'video/mp4'                                                                 => 'mp4',
'video/mpeg'                                                                => 'mpeg',
'application/oda'                                                           => 'oda',
'audio/ogg'                                                                 => 'ogg',
'video/ogg'                                                                 => 'ogg',
'application/ogg'                                                           => 'ogg',
'application/x-pkcs10'                                                      => 'p10',
'application/pkcs10'                                                        => 'p10',
'application/x-pkcs12'                                                      => 'p12',
'application/x-pkcs7-signature'                                             => 'p7a',
'application/pkcs7-mime'                                                    => 'p7c',
'application/x-pkcs7-mime'                                                  => 'p7c',
'application/x-pkcs7-certreqresp'                                           => 'p7r',
'application/pkcs7-signature'                                               => 'p7s',
'application/pdf'                                                           => 'pdf',
'application/octet-stream'                                                  => 'pdf',
'application/x-x509-user-cert'                                              => 'pem',
'application/x-pem-file'                                                    => 'pem',
'application/pgp'                                                           => 'pgp',
'application/x-httpd-php'                                                   => 'php',
'application/php'                                                           => 'php',
'application/x-php'                                                         => 'php',
'text/php'                                                                  => 'php',
'text/x-php'                                                                => 'php',
'application/x-httpd-php-source'                                            => 'php',
'image/png'                                                                 => 'png',
'image/x-png'                                                               => 'png',
'application/powerpoint'                                                    => 'ppt',
'application/vnd.ms-powerpoint'                                             => 'ppt',
'application/vnd.ms-office'                                                 => 'ppt',
'application/msword'                                                        => 'doc',
'application/vnd.openxmlformats-officedocument.presentationml.presentation' => 'pptx',
'application/x-photoshop'                                                   => 'psd',
'image/vnd.adobe.photoshop'                                                 => 'psd',
'audio/x-realaudio'                                                         => 'ra',
'audio/x-pn-realaudio'                                                      => 'ram',
'application/x-rar'                                                         => 'rar',
'application/rar'                                                           => 'rar',
'application/x-rar-compressed'                                              => 'rar',
'audio/x-pn-realaudio-plugin'                                               => 'rpm',
'application/x-pkcs7'                                                       => 'rsa',
'text/rtf'                                                                  => 'rtf',
'text/richtext'                                                             => 'rtx',
'video/vnd.rn-realvideo'                                                    => 'rv',
'application/x-stuffit'                                                     => 'sit',
'application/smil'                                                          => 'smil',
'text/srt'                                                                  => 'srt',
'image/svg+xml'                                                             => 'svg',
'application/x-shockwave-flash'                                             => 'swf',
'application/x-tar'                                                         => 'tar',
'application/x-gzip-compressed'                                             => 'tgz',
'image/tiff'                                                                => 'tiff',
'text/plain'                                                                => 'txt',
'text/x-vcard'                                                              => 'vcf',
'application/videolan'                                                      => 'vlc',
'text/vtt'                                                                  => 'vtt',
'audio/x-wav'                                                               => 'wav',
'audio/wave'                                                                => 'wav',
'audio/wav'                                                                 => 'wav',
'application/wbxml'                                                         => 'wbxml',
'video/webm'                                                                => 'webm',
'audio/x-ms-wma'                                                            => 'wma',
'application/wmlc'                                                          => 'wmlc',
'video/x-ms-wmv'                                                            => 'wmv',
'video/x-ms-asf'                                                            => 'wmv',
'application/xhtml+xml'                                                     => 'xhtml',
'application/excel'                                                         => 'xl',
'application/msexcel'                                                       => 'xls',
'application/x-msexcel'                                                     => 'xls',
'application/x-ms-excel'                                                    => 'xls',
'application/x-excel'                                                       => 'xls',
'application/x-dos_ms_excel'                                                => 'xls',
'application/xls'                                                           => 'xls',
'application/x-xls'                                                         => 'xls',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'         => 'xlsx',
'application/vnd.ms-excel'                                                  => 'xlsx',
'application/xml'                                                           => 'xml',
'text/xml'                                                                  => 'xml',
'text/xsl'                                                                  => 'xsl',
'application/xspf+xml'                                                      => 'xspf',
'application/x-compress'                                                    => 'z',
'application/x-zip'                                                         => 'zip',
'application/zip'                                                           => 'zip',
'application/x-zip-compressed'                                              => 'zip',
'application/s-compressed'                                                  => 'zip',
'multipart/x-zip'                                                           => 'zip',
'text/x-scriptzsh'                                                          => 'zsh',
'application/vnd.oasis.opendocument.text'                                   => 'odt',
'application/vnd.oasis.opendocument.spreadsheet'                            => 'ods',
'application/vnd.oasis.opendocument.presentation'                           => 'odp',
];

return isset($mime_map[$mime]) === true ? $mime_map[$mime] : '';
}


相关文章
热门推荐