thinkphp3.2.3 excel導出,下載文件,包含圖片

關於導出後出錯的問題javascript

https://segmentfault.com/q/1010000005330214php

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

我遇到了文件損壞,通過百度,大神說是緩衝區的問題,在導出函數的第一行加上html

ob_end_clean();java

相關介紹thinkphp

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

擴展下載連接segmentfault

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

本文章摘取了一下文獻瀏覽器

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();

相關文章
相關標籤/搜索