程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> 解析PHPExcel使用的常用說明以及把PHPExcel整合進CI框架的介紹

解析PHPExcel使用的常用說明以及把PHPExcel整合進CI框架的介紹

編輯:關於PHP編程

excel的寫入與生成操作:
復制代碼 代碼如下:
include 'PHPExcel.php';
include 'PHPExcel/Writer/Excel2007.php';
//或者include 'PHPExcel/Writer/Excel5.php'; 用於輸出.xls的
include 'PHPExcel/IOFactory.php';//phpexcel工廠類
//創建一個excel
$objPHPExcel = new PHPExcel();
//保存excel—2007格式
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
//也可以使用
//$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
//或者$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel); 非2007格式
$objWriter->save("xxx.xlsx");
//直接輸出到浏覽器
$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
header("Pragma: public");
header("Expires: 0″);
header("Cache-Control:must-revalidate, post-check=0, pre-check=0″);
header("Content-Type:application/force-download");
header("Content-Type:application/vnd.ms-execl");
header("Content-Type:application/octet-stream");
header("Content-Type:application/download");;
header('Content-Disposition:attachment;filename="resume.xls"');
header("Content-Transfer-Encoding:binary");
$objWriter->save('php://output');
//直接生成文件
$objWriterr->save(‘文件名');
//設置excel的屬性:
//創建人
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
//最後修改人
$objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
//標題
$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
//題目
$objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
//描述
$objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");
//關鍵字
$objPHPExcel->getProperties()->setKeywords("office 2007 openxml php");
//種類
$objPHPExcel->getProperties()->setCategory("Test result file");
//設置當前的sheet
$objPHPExcel->setActiveSheetIndex(0);
//設置sheet的name
$objPHPExcel->getActiveSheet()->setTitle('Simple');
//設置單元格的值
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'String');
$objPHPExcel->getActiveSheet()->setCellValue('A2', 12);
$objPHPExcel->getActiveSheet()->setCellValue('A3', true);
$objPHPExcel->getActiveSheet()->setCellValue('C5', '=SUM(C2:C4)');
$objPHPExcel->getActiveSheet()->setCellValue('B8', '=MIN(B2:C5)');
//合並單元格
$objPHPExcel->getActiveSheet()->mergeCells('A18:E22');
//分離單元格
$objPHPExcel->getActiveSheet()->unmergeCells('A28:B28');
//保護cell
$objPHPExcel->getActiveSheet()->getProtection()->setSheet(true); // Needs to be set to true in order to enable any worksheet protection!
$objPHPExcel->getActiveSheet()->protectCells('A3:E13', 'PHPExcel');
//設置格式
// Set cell number formats
echo date('H:i:s') . " Set cell number formats\n";
$objPHPExcel->getActiveSheet()->getStyle('E4')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE);
$objPHPExcel->getActiveSheet()->duplicateStyle( $objPHPExcel->getActiveSheet()->getStyle('E4'), 'E5:E13' );
//設置寬width
// Set column widths
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(12);
//設置font
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setName('Candara');
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setSize(20);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
$objPHPExcel->getActiveSheet()->getStyle('E1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
$objPHPExcel->getActiveSheet()->getStyle('D13')->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getStyle('E13')->getFont()->setBold(true);
//設置align
$objPHPExcel->getActiveSheet()->getStyle('D11')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
$objPHPExcel->getActiveSheet()->getStyle('D12')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
$objPHPExcel->getActiveSheet()->getStyle('D13')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
$objPHPExcel->getActiveSheet()->getStyle('A18')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY);
//垂直居中
$objPHPExcel->getActiveSheet()->getStyle('A18')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
設置column的border
$objPHPExcel->getActiveSheet()->getStyle('A4')->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getActiveSheet()->getStyle('B4')->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getActiveSheet()->getStyle('C4')->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getActiveSheet()->getStyle('D4')->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getActiveSheet()->getStyle('E4')->getBorders()->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
設置border的color
$objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getLeft()->getColor()->setARGB('FF993300');
$objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getTop()->getColor()->setARGB('FF993300');
$objPHPExcel->getActiveSheet()->getStyle('D13')->getBorders()->getBottom()->getColor()->setARGB('FF993300');
$objPHPExcel->getActiveSheet()->getStyle('E13')->getBorders()->getTop()->getColor()->setARGB('FF993300');
$objPHPExcel->getActiveSheet()->getStyle('E13')->getBorders()->getBottom()->getColor()->setARGB('FF993300');
$objPHPExcel->getActiveSheet()->getStyle('E13')->getBorders()->getRight()->getColor()->setARGB('FF993300');
設置填充顏色
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->getStartColor()->setARGB('FF808080');
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFill()->getStartColor()->setARGB('FF808080');
//加圖片
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Logo');
$objDrawing->setDescription('Logo');
$objDrawing->setPath('./images/officelogo.jpg');
$objDrawing->setHeight(36);
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Paid');
$objDrawing->setDescription('Paid');
$objDrawing->setPath('./images/paid.png');
$objDrawing->setCoordinates('B15');
$objDrawing->setOffsetX(110);
$objDrawing->setRotation(25);
$objDrawing->getShadow()->setVisible(true);
$objDrawing->getShadow()->setDirection(45);
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
//處理中文輸出問題
//需要將字符串轉化為UTF-8編碼,才能正常輸出,否則中文字符將輸出為空白,如下處理:
 $str  = iconv('gb2312', 'utf-8', $str);
或者你可以寫一個函數專門處理中文字符串:
function convertUTF8($str)
{
   if(empty($str)) return '';
   return  iconv('gb2312', 'utf-8', $str);
}

讀取excel
1.導入一個Excel最簡單的方法是使用PHPExel的IO Factory,調用PHPExcel_IOFactory類的靜態法load,它可以自動識別文檔格式,包括Excel2007、Excel2003XML、OOCalcSYLK、Gnumeric、CSV。返回一個PHPExcel的實例。
 復制代碼 代碼如下:
 //加載工廠類
include'PHPExcel/IOFactory.php';
//要讀取的xls文件路徑
$inputFileName = './sampleData/example1.xls';
/** 用PHPExcel_IOFactory的load方法得到excel操作對象  **/
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
//得到當前活動表格,調用toArray方法,得到表格的二維數組
$sheetData =$objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
var_dump($sheetData);

1.創建一個ExcelReader去加載一個Excel文檔
如果你知道這個Excel文檔的格式,可以建立一個相應的Reader去加載要讀取的Excel文檔。但是如果你加載了錯誤的文檔類型,可會產生不可預知的錯誤。
復制代碼 代碼如下:
$inputFileName = './sampleData/example1.xls';
/** Create a new Excel5 Reader  **/
$objReader = new PHPExcel_Reader_Excel5();
//    $objReader = new PHPExcel_Reader_Excel2007();
//    $objReader = new PHPExcel_Reader_Excel2003XML();
//    $objReader = new PHPExcel_Reader_OOCalc();
//    $objReader = new PHPExcel_Reader_SYLK();
//    $objReader = new PHPExcel_Reader_Gnumeric();
//    $objReader = new PHPExcel_Reader_CSV();
/** Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);
//得到當前活動sheet
$curSheet =$objPHPExcel->getActiveSheet();
//以二維數組形式返回該表格的數據
$sheetData = $curSheet->toArray(null,true,true,true);
var_dump($sheetData);

也可以用PHPExcel_IOFactory的createReader方法去得到一個Reader對象,無需知道要讀取文件的格式。
復制代碼 代碼如下:
$inputFileType = 'Excel5';
//    $inputFileType = 'Excel2007';
//    $inputFileType = 'Excel2003XML';
//    $inputFileType = 'OOCalc';
//    $inputFileType = 'SYLK';
//    $inputFileType = 'Gnumeric';
//    $inputFileType = 'CSV';
$inputFileName = './sampleData/example1.xls';
/**  Create a new Reader of the type defined in $inputFileType  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/**  Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);
//得到當前活動sheet
$curSheet = $objPHPExcel->getActiveSheet();
//以二維數組形式返回該表格的數據
$sheetData = $curSheet->toArray(null,true,true,true);
var_dump($sheetData);

如果在讀取文件之前,文件格式未知,你可以通過IOFactory 的 identify()方法得到文件類型,然後通過createReader()方法去穿件閱讀器。
復制代碼 代碼如下:
$inputFileName = './sampleData/example1.xls';
/**  確定輸入文件的格式  **/
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
/** 穿件相對應的閱讀器  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/**  加載要讀取的文件  **/
$objPHPExcel = $objReader->load($inputFileName);

2.設置Excel的讀取選項
在使用load()方法加載文件之前,可以設置讀取選項來控制load的行為.
2.1.ReadingOnly Data from a Spreadsheet File
setReadDataOnly()方法,配置閱讀器不關注表格數據的數據類型,都以string格式返回
復制代碼 代碼如下:
$inputFileType = 'Excel5';
$inputFileName = './sampleData/example1.xls';
/**  Create a new Reader of the type defined in $inputFileType  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/**  配置單元格數據都以字符串返回  **/
$objReader->setReadDataOnly(true);
/**  Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);
$sheetData =$objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
var_dump($sheetData);

返回數據:
復制代碼 代碼如下:
array(8) {
  [1]=>
  array(6) {
   ["A"]=>
   string(15) "Integer Numbers"
   ["B"]=>
    string(3)"123"
   ["C"]=>
    string(3)"234"
   ["D"]=>
    string(4)"-345"
   ["E"]=>
    string(3)"456"
    ["F"]=>
    NULL
  }
  [2]=>
  array(6) {
    ["A"]=>
    string(22) "Floating PointNumbers"
    ["B"]=>
    string(4) "1.23"
    ["C"]=>
    string(5) "23.45"
    ["D"]=>
    string(10) "0.00E+0.00"
    ["E"]=>
    string(6) "-45.68"
    ["F"]=>
    string(7) "£56.78"
  }
  [3]=>
  array(6) {
    ["A"]=>
    string(7) "Strings"
    ["B"]=>
    string(5) "Hello"
    ["C"]=>
    string(5) "World"
    ["D"]=>
    NULL
    ["E"]=>
    string(8) "PHPExcel"
    ["F"]=>
    NULL
  }
  [4]=>
  array(6) {
    ["A"]=>
    string(8) "Booleans"
    ["B"]=>
    bool(true)
    ["C"]=>
    bool(false)
    ["D"]=>
    NULL
    ["E"]=>
    NULL
    ["F"]=>
    NULL
  }
  [5]=>
  array(6) {
    ["A"]=>
    string(5) "Dates"
    ["B"]=>
    string(16) "19 December 1960"
    ["C"]=>
    string(15) "10 October 2010"
    ["D"]=>
    NULL
    ["E"]=>
    NULL
    ["F"]=>
    NULL
  }
  [6]=>
  array(6) {
    ["A"]=>
    string(5) "Times"
    ["B"]=>
    string(4) "9:30"
   ["C"]=>
    string(5) "23:59"
    ["D"]=>
    NULL
    ["E"]=>
    NULL
    ["F"]=>
    NULL
  }
  [7]=>
  array(6) {
    ["A"]=>
    string(8) "Formulae"
    ["B"]=>
    string(3) "468"
    ["C"]=>
    string(7) "-20.998"
    ["D"]=>
    NULL
    ["E"]=>
    NULL
    ["F"]=>
    NULL
  }
  [8]=>
  array(6) {
    ["A"]=>
    string(6) "Errors"
    ["B"]=>
    string(4) "#N/A"
    ["C"]=>
    string(7) "#DIV/0!"
    ["D"]=>
    NULL
    ["E"]=>
    NULL
    ["F"]=>
    NULL
  }
}
如果不設置則返回:
array(8) {
  [1]=>
  array(6) {
    ["A"]=>
    string(15) "Integer Numbers"
    ["B"]=>
    float(123)
    ["C"]=>
    float(234)
    ["D"]=>
    float(-345)
    ["E"]=>
    float(456)
    ["F"]=>
    NULL
  }
  [2]=>
  array(6) {
    ["A"]=>
    string(22) "Floating Point Numbers"
    ["B"]=>
    float(1.23)
    ["C"]=>
    float(23.45)
    ["D"]=>
    float(3.45E-6)
    ["E"]=>
    float(-45.678)
    ["F"]=>
    float(56.78)
  }
  [3]=>
  array(6) {
    ["A"]=>
    string(7) "Strings"
    ["B"]=>
    string(5) "Hello"
    ["C"]=>
    string(5) "World"
    ["D"]=>
    NULL
    ["E"]=>
    string(8) "PHPExcel"
    ["F"]=>
    NULL
  }
  [4]=>
  array(6) {
    ["A"]=>
    string(8) "Booleans"
    ["B"]=>
    bool(true)
    ["C"]=>
    bool(false)
   ["D"]=>
    NULL
    ["E"]=>
    NULL
    ["F"]=>
    NULL
  }
  [5]=>
  array(6) {
    ["A"]=>
    string(5) "Dates"
    ["B"]=>
    float(22269)
    ["C"]=>
    float(40461)
    ["D"]=>
    NULL
    ["E"]=>
    NULL
    ["F"]=>
    NULL
  }
  [6]=>
  array(6) {
    ["A"]=>
    string(5) "Times"
    ["B"]=>
    float(0.39583333333333)
    ["C"]=>
    float(0.99930555555556)
    ["D"]=>
    NULL
    ["E"]=>
    NULL
    ["F"]=>
    NULL
  }
  [7]=>
  array(6) {
    ["A"]=>
    string(8) "Formulae"
    ["B"]=>
    float(468)
    ["C"]=>
    float(-20.99799655)
    ["D"]=>
    NULL
    ["E"]=>
    NULL
    ["F"]=>
    NULL
  }
  [8]=>
  array(6) {
    ["A"]=>
    string(6) "Errors"
    ["B"]=>
    string(4) "#N/A"
    ["C"]=>
    string(7) "#DIV/0!"
    ["D"]=>
    NULL
    ["E"]=>
    NULL
    ["F"]=>
    NULL
  }
}

Reading Only Data from a SpreadsheetFile applies to Readers:
       Excel2007      YES         Excel5            YES         Excel2003XML YES
       OOCalc          YES         SYLK              NO          Gnumeric       YES
       CSV         NO

2.2.ReadingOnly Named WorkSheets from a File
setLoadSheetsOnly(),設置要讀取的worksheet,接受worksheet的名稱作為參數。
復制代碼 代碼如下:
/** PHPExcel_IOFactory */
include'PHPExcel/IOFactory.php';
$inputFileType = 'Excel5';
//  $inputFileType = 'Excel2007';
//  $inputFileType = 'Excel2003XML';
//  $inputFileType = 'OOCalc';
//  $inputFileType = 'Gnumeric';
$inputFileName ='./sampleData/example1.xls';
$sheetname = 'Data Sheet #2';

echo 'Loading file',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with a definedreader type of ',$inputFileType,'<br />';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
echo 'Loading Sheet"',$sheetname,'" only<br />';
$objReader->setLoadSheetsOnly($sheetname);
$objPHPExcel =$objReader->load($inputFileName);
echo '<hr />';
echo$objPHPExcel->getSheetCount(),' worksheet',(($objPHPExcel->getSheetCount()== 1) ? '' : 's'),' loaded<br /><br />';
$loadedSheetNames =$objPHPExcel->getSheetNames();
foreach($loadedSheetNames as$sheetIndex => $loadedSheetName) {
    echo $sheetIndex,' -> ',$loadedSheetName,'<br />';
}

如果想讀取多個worksheet,可以傳遞一個數組
復制代碼 代碼如下:
$inputFileType = 'Excel5';
$inputFileName = './sampleData/example1.xls';
$sheetnames = array('Data Sheet #1','Data Sheet #3');
/**  Create a new Reader of the type defined in $inputFileType  **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/**  Advise the Reader of which WorkSheets we want to load  **/
$objReader->setLoadSheetsOnly($sheetnames);
/**  Load $inputFileName to a PHPExcel Object  **/
$objPHPExcel = $objReader->load($inputFileName);

如果想讀取所有worksheet,可以調用setLoadAllSheets()。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved