PHPEcel 簡單使用

關于phpexcel 的簡單使用 整理經常用的幾個方法

后臺數據有時候需要導出成excel 公司對賬或者統計用, 這時候后臺操作就需要對數據進行導出功能, php用到的就是phpexcel這個三方類庫了, 不過這個對服務器要求比較高, 大批量數據處理需要多方面處理.

  1. 第一步先下載phpexcel 三方庫

  2. 這里直接上代碼, 只是簡單的幾個使用情況, 自己根據情況修改吧, 百度phpexce使用很多. 代碼如下

include "PHPExcel.php";

/**
 * 文件路徑讀取Excel模板
 * @param string $path
 * @return object
 */
function getExcelObjectByPath($path)
{
    if(empty($path) or !file_exists($path)){

        die('file not exists');

    }

    $PHPReader = new PHPExcel_Reader_Excel2007();

    if(!$PHPReader->canRead($path)){
        $PHPReader = new PHPExcel_Reader_Excel5();

        if(!$PHPReader->canRead($path)){
            echo 'no Excel';

            return ;
        }
    }
    $PHPExcel = $PHPReader->load($path);

    return $PHPExcel;
}

讀取本地excel文件轉換成excel對象返回

/**
 * PHPExcel轉換為數組
 * @param object $PHPExcel
 * @param int $startRow
 * @param int $endRow
 * @param int $sheet
 * @return array
 */
function excelToData($PHPExcel, $startRow = 1,  $endRow = 0, $sheet = 0)
{
    /** 讀取excel文件中的指定工作表 */
    $currentSheet = $PHPExcel->getSheet($sheet);

    /** 取得最大的列號 */
    $maxColumn = $currentSheet->getHighestColumn();

    /** 取得一共有多少行 */
    $maxRow = $currentSheet->getHighestRow() - $endRow;

    $data = array();

    $rowIndex = $startRow;

    /** 循環讀取每個單元格的內容。 列從A開始 */
    for ($rowIndex; $rowIndex <= $maxRow; $rowIndex++)
    {
        $data_row = array();
        for($colIndex ='A'; $colIndex <= $maxColumn; $colIndex++)
        {

            $addr = $colIndex.$rowIndex;
            $cell = $currentSheet->getCell($addr)->getValue();
            if($cell instanceof PHPExcel_RichText)
            {
                /** 富文本轉換字符串 */
                $cell = $cell->__toString();
            }

            /** 判斷單元格內容是否為公式 */
            $cell_one = substr($cell, 0, 1);

            if($cell_one == '=')
            {
                /** 取公式計算后的結果 */
                $value = $currentSheet->getCell($addr)->getFormattedValue();
                $cell = $value;
            }


            $data_row[] = $cell;



        }

        $data[] = $data_row;

    }


    return $data;
}

/**
 * PHPExcel生成并添加內容
 * @param array $content
 * @param array $title
 * @param int $startRow
 * @param int $sheet
 * @param int $type
 * @return object
 */
function importDataForObj($content = array(), $title = array(), $startRow = 1, $sheet = 0, $type = 2007){


    $PHPExcel = new PHPExcel();

    /** 07版參數設置 */
    if ($type == 2007)
    {
        $PHPExcel->getProperties()->setCreator("ctos")
            ->setLastModifiedBy("ctos")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
    }


    /** 讀取excel文件中的指定工作表 */
    $currentSheet = $PHPExcel->getSheet($sheet);

    /** 設置工作薄名稱 */
    $currentSheet->setTitle(iconv('gbk', 'utf-8', 'test'));
    /** 設置插入起始行數, 這里用獲取的行數計算。可以自行根據模板進行設置固定數值 */

    $startColumn = "A";
    if (!empty($title))
    {
        foreach ($title as $item)
        {
            /** 設置寬cell寬 */
            $currentSheet->getColumnDimension($startColumn)->setWidth(18);
            /** 對齊方式 */
            $currentSheet->getStyle($startColumn)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY);
            /** 為標題賦值 */
            $currentSheet->setCellValue($startColumn . "1", $item);
            $startColumn++;
        }

        $startRow++;
    }

    $i = $startRow;
    /** 寫入數據 */
    foreach($content as $data)
    {
        $startColumn = 'A';
        foreach($data as $value)
        {
            /** excel科學計數很煩 這里舉例簡單實用解決方式 拼接空字符串 */
            if($startColumn == 'A')
            {
                $currentSheet->setCellValue($startColumn . $i, " ".$value);

            } else
            {
                $currentSheet->setCellValue($startColumn . $i, $value);
            }


            $startColumn++;

        }

        $i++;

    }

    return $PHPExcel;

}


/**
 * PHPExcel轉換為數組
 * @param object $PHPExcel
 * @param string $filename
 * @param string $ex
 */

function download($PHPExcel,  $filename = 'HelloWord', $ex = '2007')
{
    ob_end_clean();

    /** 導出excel2007文檔*/
    if($ex == '2007') {
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;

        /** 導出excel2003文檔 */
    } else if ($ex == '2005'){

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    } else if ($ex == 'pdf')
    {

        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment;filename="'.$filename.'.pdf"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($PHPExcel, 'PDF');
        $objWriter->setFont('arialunicid0-chinese-simplified');
        $objWriter->save('php://output');
        exit;

    } else if ($ex == 'csv')
    {

        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename.'.csv');
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        $objWriter = PHPExcel_IOFactory::createWriter($PHPExcel, 'CSV');
        $objWriter->setFont('arialunicid0-chinese-simplified');
        $objWriter->save('php://output');
        exit;
    }


}
image.png

需要說明一下 這里賦值拼接一個空字符串" "解決excel科學計數問題簡單實用

image.png

這個方法是解決excel內存在公式問題

image.png

這個把excel轉換成pdf 樣式很逗(phpexcel 我之前下過一版并不能使用這個方法, 如遇到問題可聯系我)

平時我就用這幾個方法就夠用了, 分享一下方便大家使用.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,466評論 25 708
  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,251評論 4 61
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,981評論 19 139
  • 一、引言 最近幾年,隨著“互聯網+”概念的興起,越來越多的企業開始涉足互聯網,運用互聯網工具幫助自身轉型升級,提高...
    唐大虞閱讀 14,193評論 0 5
  • 人與人之間的差異,其實很簡單:你在賴床,他在鍛煉,所以他比你健康;你在應付上班,他在用心工作,所以他成了你的領導;...
    小鹿says閱讀 167評論 0 0