1. 程式人生 > >php excel檔案線上預覽(走過的坑)

php excel檔案線上預覽(走過的坑)

首先感謝以往分享相關問題的小夥伴,從中收貨很多部分內容也是引用了前人的內容,希望對後來的人有幫助。

1.已經布好的服務如微軟的Office365等平臺服務

	 例項:http://technet.microsoft.com/zh-cn/library/jj219456(v=office.15).aspx  只需要將自己檔案地址傳進去即可
	 這種處理方式雖然方便,但是對於公司的資料資源的保護不利,並且這些線上轉換服務是收費的,如果這方面無所謂的話推薦使用。

2.通過phpExcel擴充套件進行excel檔案解析直接輸出html

不推薦: 通過檔案字尾名switch case 方式建立createReader讀取,這種方式不能準確的判斷檔案型別導致經常會讀取錯誤,這一點很重要。 當excel中有圖片解析報錯未解決如果有同學解決了這個問題希望能分享出來

	set_time_limit(0);
	require dirname(dirname(__FILE__)) . '../../common/comp/excel/PHPExcel.php'; //更改為你的phpexcel檔案地址     
	$sFileUrl=>''// 你檔案的地址
	$sFileType = PHPExcel_IOFactory::identify($sFileUrl);//獲取檔案型別
	$objReader = PHPExcel_IOFactory::createReader($sFileType);//建立讀取
	$objWriteHtml=new PHPExcel_Writer_HTML($objReader->load($sFileUrl, 'UTF-8'));//載入內容
	echo $objWriteHtml->save("php://output");//輸出html檔案到頁面

3通過openoffice進行檔案解析轉換->pdf->swf

首先安裝oppenoffice服務並且後臺啟用服務,windows平臺需要安裝完openOffice後,在開始–執行中輸入Dcomcnfg開啟元件服務。在元件服務—計算機—我的電腦—DCOMP配置中,選擇openoffice service manager右鍵屬性->安全 全部新增組或使用者名稱Everyone,屬性->標識 選擇互動式使用者,linux系統配置自行查詢一下相對windows要簡單很多(此步驟解決報錯)

執行命令: soffice -headless-accept=“socket,host=127.0.0.1,port=8100;urp;” -nofirststartwizard 成功後即在後臺運行了該軟體。

如果是php5.4.5以前版本,需要在php.ini裡把com.allow_dcom = true開啟,即去掉前面的分號。如果是以後版本,需要在php.ini 裡增加一行擴充套件extension=php_com_dotnet.dll,然後檢查php的ext目錄中是否存在該dll檔案,如果沒有請自行下載對應版本的dll。然後重啟apache

下面是通過php方式呼叫openoffice生成pdf swf,推薦單獨建立java服務網上相關的資料也更多一些,輸入輸出檔案路徑使用絕對路徑,但是有一個問題csv檔案會出現轉換亂碼未解決

<?php
/**
 * office文件轉換類
 * 實現office任何格式文件網頁瀏覽
 * author hui
 * 1,安裝OpenOffice 4.1.3 (zh-CN)
 *
 * 2,安裝 SWFTOOLS http://www.swftools.org/download.html
 *   並把pdf2swf.exe檔案移動到C盤根目錄
 *
 * 3,php.ini 開啟com.allow_dcom = true
 *   php.ini 新增extension=php_com_dotnet.dll
 *   檢查該檔案
 *   php/ext/php_com_dotnet.dll
 */

class Convert{
    
    private $osm;
    
    // 建構函式,啟用OpenOffice的COM元件
    public function __construct(){
        ini_set('magic_quotes_runtime', 0); // 設定執行時間
        $this->osm = new COM("com.sun.star.ServiceManager") or die("Please be sure that OpenOffice.org is installed.n");
    }
    
    private function MakePropertyValue($name, $value) {
        $oStruct = $this->osm->Bridge_GetStruct("com.sun.star.beans.PropertyValue");
        $oStruct->Name = $name;
        $oStruct->Value = $value;
        return $oStruct;
    }
    
    private function transform($input_url, $output_url) {
        $args = array($this->MakePropertyValue('Hidden', true));
        $oDesktop = $this->osm->createInstance("com.sun.star.frame.Desktop");
        $oWriterDoc = $oDesktop->loadComponentFromURL($input_url, '_blank', 0, $args);
        $export_args = array($this->MakePropertyValue('FilterName', 'writer_pdf_Export'));
        $oWriterDoc->storeToURL($output_url, $export_args);
        $oWriterDoc->close(true);
//        return $this->getPdfPages($output_url);
    }
    
    /**
     * getPdfPages 獲取PDF檔案頁數的函式獲取,檔案應當對當前使用者可讀(linux下)
     * @param  string $path 檔案路徑
     * @return int
     */
    private function getPdfPages($path = '') {
        if(!file_exists($path)) return 0;
        if(!is_readable($path)) return 0;
        [email protected]($path, "r"); // 開啟檔案
        if(!$fp){
            return 0;
        }else{
            $max = 0;
            while(!feof($fp)) {
                $line = fgets($fp,255);
                if(preg_match('/\/Count [0-9]+/', $line, $matches)){
                    preg_match('/[0-9]+/', $matches[0], $matches2);
                    if ($max<$matches2[0]) $max = $matches2[0];
                }
            }
            fclose($fp);
            return $max; // 返回頁數
        }
    }
    
    /**
     * office檔案轉換pdf格式
     * @param  string $input  需要轉換的檔案
     * @param  string $output 轉換後的pdf檔案
     * @return return string 頁數
     */
    public function run($input = '', $output = '') {
        if(empty($input) || empty($output)) {
            return ['error' => 1, 'msg' => '引數缺失', 'flag' => 'run'];
        }
//        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
//            $encoding = 'UCS-2LE';
//        else
//            $encoding = 'UCS-2BE';
        $input      = "file:///" . str_replace("\\", "/", $input);
        $output     = "file:///" . str_replace("\\", "/", $output);
//        $oldEncoding   = mb_detect_encoding($input);
//        return $this->transform(iconv($encoding, $oldEncoding, $input), iconv($encoding, $oldEncoding, $output));
//        $oObj = $this->transform($input, $output);
//        var_dump($oObj);exit;
        return $this->transform($input, $output);
    }
    
    /**
     * pdf2swf pdf檔案轉換swf格式
     * @param  string $word_file  需要轉換的檔案路徑
     * @param  string $attach_dir 儲存檔案地址
     * @return array
     */
    public function pdf2swf($word_file = '', $attach_dir = '') {
        if(empty($word_file) || empty($attach_dir)){
            return ['error' => 1, 'msg' => '引數缺失', 'flag' => 'pdf2swf'];
        }
        $file_name = uniqid();
        $pdf_file =  "{$attach_dir}{$file_name}.pdf";                                         // PDF檔案絕對路徑
        $page = $this->run($word_file, $pdf_file);                                             // 檔案先轉換為PDF格式
        if(isset($page) && $page > 0){
            $swf_file = "{$attach_dir}{$file_name}.swf";                                     // 轉換後的swf檔案
            $pd = str_replace("/", "\\", $pdf_file);
            $sw = str_replace("/", "\\", $swf_file);
            $cmd = Config::get('websetup.swftools') . " -t {$pd} -s flashversion=9 -o {$sw}";
            $phpwsh = new COM("Wscript.Shell") or die("Create Wscript.Shell Failed!");
            $exec = $phpwsh->exec("cmd.exe /c" . $cmd);                                     // cmd執行pdf2swf轉換命令
            $stdout = $exec->stdout();
            $stdout->readall();
            if(is_file($sw)){                                                                 // swf檔案
                if(is_file($pdf_file)){                                                     // 刪除pdf檔案
                    unlink($pdf_file);
                }
                return ['error' => 0, 'page' => $page, 'swf_file' => $file_name];
            }else{
                return ['error' => 1, 'msg' => 'swf檔案不存在', 'flag' => 'pdf2swf'];
            }
        }else{
            return ['error' => 1, 'msg' => '轉換pdf失敗', 'flag' => 'pdf2swf'];
        }
    }
}

4.讀取excel檔案資料返回給前端

前端樣式可控性強

$aReturnData = [
    'title_name' => '',
    'data_list' => []
];
$sFileType = PHPExcel_IOFactory::identify($sFileUrl);
$objReader = PHPExcel_IOFactory::createReader($sFileType);
$objPHPExcel = $objReader->load($sFileUrl, 'UTF-8');
$aSheetNames = $objPHPExcel->getSheetNames();
foreach ($aSheetNames as $iKey => $sSheetName) {
	$oSheet = $objPHPExcel->getSheet($iKey);
	$iColumn= $oSheet->getHighestColumn();
	$iRow   = $oSheet->getHighestRow();
	for ($i = 1; $i <= $iRow; $i++) {
	    $aTmp = [];
	    for ($j = 'A'; $j <= $iColumn; $j++) {
	        $sTmp = $oSheet->getCell($j.$i)->getValue();
	        $aTmp[] = empty($sTmp)?'':$sTmp;
	    }
	    $aReturnData['data_list'][$sSheetName][] = $aTmp;
	}
}