thinkphp3.2.3 excel导出,下载文件,包含图片

关于导出后出错的问题

https://segmentfault.com/q/1010000005330214

https://blog.csdn.net/ohmygirl/article/details/6907946

我遇到了文件损坏,经过百度,大神说是缓冲区的问题,在导出函数的第一行加上

ob_end_clean();

相关介绍

https://blog.csdn.net/soonfly/article/details/52103795

扩展下载链接

https://pan.baidu.com/s/1yPzl7dKZ-CT6DNi9SUt6kg

本文章摘取了一下文献

http://www.thinkphp.cn/code/1257.html

thinkphp3.2和phpexcel导入
http://www.thinkphp.cn/code/2124.html

thinkphp3.2和phpexcel导入,出现PHPExcel_RichText object解决办法
http://www.thinkphp.cn/code/2143.html

thinkphp3.2和phpexcel导出带生成图片完美案例
http://www.thinkphp.cn/code/2112.html

 

第一步:下载PHPEXCEL文件(这个可以百度下载)




第二步:解压这个文件,把这里全部的文件复制到 ThinkPHP/Library/Org/Util
这个文件夹下面(如图所示), 并把 PHPExcel.php 这个文件改名为 PHPExcel.class.php



第三步:如何使用




通过上面的代码,已经成功导出一下excel文件

生成excel的代码如下和上面图片类似

public function imgexcel(){
     ob_end_clean(); import(
"Org.Util.PHPExcel"); $excel = new \PHPExcel(); $excel->getProperties()->setCreator("JAMES") ->setLastModifiedBy("JAMES") ->setTitle("zltrans") ->setSubject("Dorder") ->setDescription("Dorder List") ->setKeywords("Dorder") ->setCategory("Test result file"); $excel->setActiveSheetIndex(0) ->setCellValue("A1","hello") ->setCellValue("A3","龙龙") ->setCellValue("B2","你好") ->setCellValue("B4","世界"); import("Org.Util.PHPExcel.IOFactory"); $excelWriter = \PHPExcel_IOFactory::createWriter($excel,'Excel2007');
//转码文件名,防止汉字乱码
$filename = iconv("utf-8","gb2312","guagua龙.xlsx"); $excelWriter->save($filename);//使用下载方法一的时候注释 $this->force_download($filename);//使用下载方法一的时候注释
}

下载方法一:

header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$filename\"");//文件名
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
        $objWriter->save('php://output'); //文件通过浏览器下载

 

 下载方法二:

导出到了服务器上,如果需要下载到客户端的话如下:

//下面两个是下载需要的函数
public function force_download($filename)
    {
        if ($filename == ''){
            return FALSE;
        }
        if (FALSE === strpos($filename, '.')){
            return FALSE;
        }
        $x = explode('.', $filename);
        $extension = end($x);
        $mimes =$this->getMimes();
        // Set a default mime if we can't find it
        if ( ! isset($mimes[$extension])){
            $mime = 'application/octet-stream';
        }else{
            $mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
        }
        // Generate the server headers
        if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== FALSE)
        {
            header('Content-Type: "'.$mime.'"');
            header('Content-Disposition: attachment; filename="'.$filename.'"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header("Content-Transfer-Encoding: binary");
            header('Pragma: public');
            header("Content-Length: ".filesize($filename));
        }
        else
        {
            header('Content-Type: "'.$mime.'"');
            header('Content-Disposition: attachment; filename="'.$filename.'"');
            header("Content-Transfer-Encoding: binary");
            header('Expires: 0');
            header('Pragma: no-cache');
            header("Content-Length: ".filesize($filename));
        }
        readfile($filename);
    }
    private function getMimes(){
        return $mimes = array(    'hqx'    =>    'application/mac-binhex40',
            'cpt'    =>    'application/mac-compactpro',
            'csv'    =>    array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel'),
            'bin'    =>    'application/macbinary',
            'dms'    =>    'application/octet-stream',
            'lha'    =>    'application/octet-stream',
            'lzh'    =>    'application/octet-stream',
            'exe'    =>    array('application/octet-stream', 'application/x-msdownload'),
            'class'    =>    'application/octet-stream',
            'psd'    =>    'application/x-photoshop',
            'so'    =>    'application/octet-stream',
            'sea'    =>    'application/octet-stream',
            'dll'    =>    'application/octet-stream',
            'oda'    =>    'application/oda',
            'pdf'    =>    array('application/pdf', 'application/x-download'),
            'ai'    =>    'application/postscript',
            'eps'    =>    'application/postscript',
            'ps'    =>    'application/postscript',
            'smi'    =>    'application/smil',
            'smil'    =>    'application/smil',
            'mif'    =>    'application/vnd.mif',
            'xls'    =>    array('application/excel', 'application/vnd.ms-excel', 'application/msexcel'),
            'ppt'    =>    array('application/powerpoint', 'application/vnd.ms-powerpoint'),
            'wbxml'    =>    'application/wbxml',
            'wmlc'    =>    'application/wmlc',
            'dcr'    =>    'application/x-director',
            'dir'    =>    'application/x-director',
            'dxr'    =>    'application/x-director',
            'dvi'    =>    'application/x-dvi',
            'gtar'    =>    'application/x-gtar',
            'gz'    =>    'application/x-gzip',
            'php'    =>    'application/x-httpd-php',
            'php4'    =>    'application/x-httpd-php',
            'php3'    =>    'application/x-httpd-php',
            'phtml'    =>    'application/x-httpd-php',
            'phps'    =>    'application/x-httpd-php-source',
            'js'    =>    'application/x-javascript',
            'swf'    =>    'application/x-shockwave-flash',
            'sit'    =>    'application/x-stuffit',
            'tar'    =>    'application/x-tar',
            'tgz'    =>    array('application/x-tar', 'application/x-gzip-compressed'),
            'xhtml'    =>    'application/xhtml+xml',
            'xht'    =>    'application/xhtml+xml',
            'zip'    =>  array('application/x-zip', 'application/zip', 'application/x-zip-compressed'),
            'mid'    =>    'audio/midi',
            'midi'    =>    'audio/midi',
            'mpga'    =>    'audio/mpeg',
            'mp2'    =>    'audio/mpeg',
            'mp3'    =>    array('audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'),
            'aif'    =>    'audio/x-aiff',
            'aiff'    =>    'audio/x-aiff',
            'aifc'    =>    'audio/x-aiff',
            'ram'    =>    'audio/x-pn-realaudio',
            'rm'    =>    'audio/x-pn-realaudio',
            'rpm'    =>    'audio/x-pn-realaudio-plugin',
            'ra'    =>    'audio/x-realaudio',
            'rv'    =>    'video/vnd.rn-realvideo',
            'wav'    =>    array('audio/x-wav', 'audio/wave', 'audio/wav'),
            'bmp'    =>    array('image/bmp', 'image/x-windows-bmp'),
            'gif'    =>    'image/gif',
            'jpeg'    =>    array('image/jpeg', 'image/pjpeg'),
            'jpg'    =>    array('image/jpeg', 'image/pjpeg'),
            'jpe'    =>    array('image/jpeg', 'image/pjpeg'),
            'png'    =>    array('image/png',  'image/x-png'),
            'tiff'    =>    'image/tiff',
            'tif'    =>    'image/tiff',
            'css'    =>    'text/css',
            'html'    =>    'text/html',
            'htm'    =>    'text/html',
            'shtml'    =>    'text/html',
            'txt'    =>    'text/plain',
            'text'    =>    'text/plain',
            'log'    =>    array('text/plain', 'text/x-log'),
            'rtx'    =>    'text/richtext',
            'rtf'    =>    'text/rtf',
            'xml'    =>    'text/xml',
            'xsl'    =>    'text/xml',
            'mpeg'    =>    'video/mpeg',
            'mpg'    =>    'video/mpeg',
            'mpe'    =>    'video/mpeg',
            'qt'    =>    'video/quicktime',
            'mov'    =>    'video/quicktime',
            'avi'    =>    'video/x-msvideo',
            'movie'    =>    'video/x-sgi-movie',
            'doc'    =>    'application/msword',
            'docx'    =>    array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'),
            'xlsx'    =>    array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip'),
            'word'    =>    array('application/msword', 'application/octet-stream'),
            'xl'    =>    'application/excel',
            'eml'    =>    'message/rfc822',
            'json' => array('application/json', 'text/json')
        );
    }

 下面是导出excel带图片的代码

这个代码的使用环境是图片全部是网络图片,需要下载下来,然后在将图片放进excel,如果是本地图片可以直接169行参数写完整的图片路径即可

以下代码是写在thingphp3.2的function.php里面的

  1 /**
  2      * 判断文件夹是否存在,不存在则创建,支持递归试的多目录创建
  3      * @param  [type]  $dir [description]
  4      * @return boolean      [description]
  5      */
  6     function z_is_dir($dir=''){
  7         $dir = "./excelimgs";
  8         if(empty($dir)){
  9             return false;
 10         }else{
 11             if(is_dir($dir)){
 12                 return true;
 13             }else{
 14                 $dir = iconv("UTF-8","GBK",$dir);
 15                 return mkdir($dir,0777,true);
 16             }
 17         }
 18     }
 19     /**
 20      * 下载图片到指定目录
 21      * @return [type] [description]
 22      */
 23     function imgdown($url='',$dir=''){
 24         if(!preg_match('/\/([^\/]+\.[a-z]{3,4})$/i',$url,$matches)){
 25             return false;
 26         }
 27         //判断目录有效性
 28         if(!z_is_dir($dir)){
 29             return false;
 30         }
 31         
 32         $image_name = strToLower($matches[1]);
 33         $ch = curl_init ($url);
 34         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 35         curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
 36         $img = curl_exec ($ch);
 37         curl_close ($ch);
 38         $fp = fopen($dir.$image_name,'w');//保存的文件名称用的是链接里面的名称
 39         // dump($image_name);die;
 40         fwrite($fp, $img);
 41         fclose($fp);
 42     }
 43     /**
 44      * excel导出  图片文件
 45      * @return [type] [description]
 46      */
 47     function look_down($data='',$dir=''){
 48         //以下是数据格式
 49 //      $data[] = array(
 50 //          'addtime'=>' 2018/03/05 12:23',
 51 //          'address'=>'平顶山卫东区新华路南环路明珠花园',
 52 //          'car_code'=>'豫D38880',
 53 //          'shenhe'=>'小明',
 54 //          'zhidan'=>'小强',
 55 //          'price'=>'5',
 56 //          'img'=>array(
 57 //              '图片链接http://p6t.clouddn.com/5acdb30.png',
 58 //              '图片链接http://p6t.clouddn.com/5acdb30.png',
 59 //              '图片链接http://p6t.clouddn.com/5acdb30.png',
 60 //              '图片链接http://p6t.clouddn.com/5acdb30.png',
 61 //              '图片链接http://p6t.clouddn.com/5acdb30.png'
 62 //              )
 63 //          );
 64 //      $data[] = array(
 65 //          'addtime'=>' 2018/08/05 12:23',
 66 //          'address'=>'郑州市卫东区新华路南环路明珠花园',
 67 //          'car_code'=>'豫D38X80',
 68 //          'shenhe'=>'小红',
 69 //          'zhidan'=>'小刚',
 70 //          'price'=>'5',
 71 //          'img'=>array(
 72 //              '图片链接http://p6t.clouddn.com/5acdb30.png',
 73 //              '图片链接http://p6t.clouddn.com/5acdb30.png',
 74 //              '图片链接http://p6t.clouddn.com/5acdb30.png',
 75 //              '图片链接http://p6t.clouddn.com/5acdb30.png',
 76 //              '图片链接http://p6t.clouddn.com/5acdb30.png'
 77 //              )
 78 //          );
 79         if(empty($data) || empty($dir)){
 80             E('数据或者路径不能为空;数据格式请进入本方法看注释;路径需要根目录开始的路径,如:./excelimgs/');
 81             return false;
 82         }
 83         //将所有包含的图片下载下来
 84         foreach ($data as $k => $v) {
 85             $imgs = $v['img'];
 86             $img_str = null;
 87             foreach ($imgs as $kk => $vv) {
 88                 $this->imgdown($vv,$dir);
 89                 //在下载的过程中将文件名单独摘出来,用于生成excel的时候要的文件名
 90                 $img_str[] = substr($vv,strripos($vv,"/")+1);
 91             }
 92             $data[$k]['img_str'] = $img_str;
 93         }
 94         
 95         // 导出Exl
 96         import("Org.Util.PHPExcel");
 97         import("Org.Util.PHPExcel.Worksheet.Drawing");
 98         import("Org.Util.PHPExcel.Writer.Excel2007");
 99         $objPHPExcel = new \PHPExcel();
100         
101         $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
102     
103         $objActSheet = $objPHPExcel->getActiveSheet();
104         
105         // 水平居中(位置很重要,建议在最初始位置)
106         $objPHPExcel->setActiveSheetIndex(0)->getStyle('A')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
107         $objPHPExcel->setActiveSheetIndex(0)->getStyle('B')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
108         $objPHPExcel->setActiveSheetIndex(0)->getStyle('C')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
109         $objPHPExcel->setActiveSheetIndex(0)->getStyle('D')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
110         $objPHPExcel->setActiveSheetIndex(0)->getStyle('E')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
111         $objPHPExcel->setActiveSheetIndex(0)->getStyle('F')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
112         $objPHPExcel->setActiveSheetIndex(0)->getStyle('G')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
113         $objPHPExcel->setActiveSheetIndex(0)->getStyle('H')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
114         $objPHPExcel->setActiveSheetIndex(0)->getStyle('I')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
115         $objPHPExcel->setActiveSheetIndex(0)->getStyle('J')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
116         $objPHPExcel->setActiveSheetIndex(0)->getStyle('K')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
117         
118         $objActSheet->setCellValue('A1', '时间');
119         $objActSheet->setCellValue('B1', '地点');
120         $objActSheet->setCellValue('C1', '车牌号');
121         $objActSheet->setCellValue('D1', '制单人');
122         $objActSheet->setCellValue('E1', '审核人');
123         $objActSheet->setCellValue('F1', '奖励金');
124         $objActSheet->setCellValue('G1', '图片');
125         $objActSheet->setCellValue('H1', '图片');
126         $objActSheet->setCellValue('I1', '图片');
127         $objActSheet->setCellValue('J1', '图片');
128         $objActSheet->setCellValue('K1', '图片');
129         // 设置个表格宽度
130         $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
131         $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(80);
132         $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
133         $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
134         $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
135         $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
136         $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(30);
137         $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30);
138         $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(30);
139         $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(30);
140         $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(30);
141         
142         // 垂直居中
143         $objPHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
144         $objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
145         $objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
146         $objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
147         $objPHPExcel->getActiveSheet()->getStyle('E')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
148         $objPHPExcel->getActiveSheet()->getStyle('F')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
149         $objPHPExcel->getActiveSheet()->getStyle('G')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
150         $objPHPExcel->getActiveSheet()->getStyle('H')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
151         $objPHPExcel->getActiveSheet()->getStyle('I')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
152         $objPHPExcel->getActiveSheet()->getStyle('J')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
153         $objPHPExcel->getActiveSheet()->getStyle('K')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
154         
155         foreach($data as $k=>$v){
156             $k +=2;
157             // 表格内容
158             $objActSheet->setCellValue('A'.$k, $v['addtime']);    
159             $objActSheet->setCellValue('B'.$k, $v['address']);                
160             $objActSheet->setCellValue('C'.$k, $v['car_code']); 
161             $objActSheet->setCellValue('D'.$k, $v['shenhe']);    
162             $objActSheet->setCellValue('E'.$k, $v['zhidan']);    
163             $objActSheet->setCellValue('F'.$k, $v['price']."元");
164             $lies = array('G','H','I','J','K');
165             $lies_index = 0;
166             foreach ($v['img_str'] as $kk => $vv) {
167                 // 图片生成
168                 $objDrawing[$k] = new \PHPExcel_Worksheet_Drawing();
169                 $objDrawing[$k]->setPath($dir.$vv);
170                 // 设置宽度高度
171                 $objDrawing[$k]->setHeight(80);//照片高度
172                 $objDrawing[$k]->setWidth(80); //照片宽度
173                 /*设置图片要插入的单元格*/
174                 $objDrawing[$k]->setCoordinates($lies[$lies_index].$k);
175                 // 图片偏移距离
176                 $objDrawing[$k]->setOffsetX(0);
177                 $objDrawing[$k]->setOffsetY(0);
178                 $objDrawing[$k]->setWorksheet($objPHPExcel->getActiveSheet());
179                 $lies_index++;
180             }
181 
182 
183             // 表格高度
184             $objActSheet->getRowDimension($k)->setRowHeight(80);
185             
186         }
187         
188         $fileName = '报价表';
189         $date = date("Y-m-d",time());
190         $fileName .= "_{$date}.xls";
191         $fileName = iconv("utf-8", "gb2312", $fileName);
192         //重命名表
193         // $objPHPExcel->getActiveSheet()->setTitle('test');
194         //设置活动单指数到第一个表,所以Excel打开这是第一个表
195         $objPHPExcel->setActiveSheetIndex(0);
196         header('Content-Type: application/vnd.ms-excel');
197         header("Content-Disposition: attachment;filename=\"$fileName\"");
198         header('Cache-Control: max-age=0');
199         $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
200         $objWriter->save('php://output'); //文件通过浏览器下载
201         // END    
202     }

 如果文件损坏,可以在导出的方法的第一行加入ob_end_clean();

转载于:https://www.cnblogs.com/zonglonglong/p/8819989.html

你可能感兴趣的:(thinkphp3.2.3 excel导出,下载文件,包含图片)