在學PHPExcel的時候,在網上查了很多資料,花了很多時間,下面是我想要分享給大家的,我找到的並進行了一定修改的親身實踐成功的資料,希望大家對大家有所幫助。
首先,需要下載PhpExcel資料,下載資料可以在這裡下載,http://download.csdn.net/detail/www122930/9207061
第一,將PHPExcel文件夾,和PHPExcel.php文件放在,一個新建的文件夾Excel中,將Excel文件夾放在,E:\Workspace\PHP\thinkphp2\ThinkPHP\Extend\Vendor,E:\Workspace\PHP\thinkphp2\這一部分是你創建Thinkphp的工作目錄。
第二,編寫一個ExcelToArray.class.php文件,將它放在E:\Workspace\PHP\thinkphp2\ThinkPHP\Extend\Library\ORG\Util,這個目錄下,ExcelToArray.class.php文件的源代碼如下:
<?php
class ExcelToArray {
public function __construct() {
Vendor("Excel.PHPExcel");//引入phpexcel類(注意你自己的路徑)
Vendor("Excel.PHPExcel.IOFactory");
}
public function read($filename,$encode,$file_type){
if(strtolower ( $file_type )=='xls')//判斷excel表類型為2003還是2007
{
Vendor("Excel.PHPExcel.Reader.Excel5");
$objReader = PHPExcel_IOFactory::createReader('Excel5');
}elseif(strtolower ( $file_type )=='xlsx')
{
Vendor("Excel.PHPExcel.Reader.Excel2007");
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
}
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($filename);
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$excelData = array();
for ($row = 1; $row <= $highestRow; $row++) {
for ($col = 0; $col < $highestColumnIndex; $col++) {
$excelData[$row][] =(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
}
}
return $excelData;
}
public function push($data,$name='Excel'){
error_reporting(E_ALL);
//date_default_timezone_set('Europe/London');
$objPHPExcel = new PHPExcel();
/*以下是一些設置 ,什麼作者 標題啊之類的*/
$objPHPExcel->getProperties()->setCreator("轉彎的陽光")
->setLastModifiedBy("轉彎的陽光")
->setTitle("usertable")
->setSubject("數據EXCEL導出")
->setDescription("備份數據")
->setKeywords("excel")
->setCategory("result file");
//
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'username')
->setCellValue('B1', 'password')
->setCellValue('C1', 'sex');
/*以下就是對處理Excel裡的數據, 橫著取數據,主要是這一步,其他基本都不要改*/
for ($i = 0; $i < count($data) - 1; $i++) {
$objPHPExcel->getActiveSheet(0)->setCellValue('A' . ($i + 2), $data[$i]['username']);
$objPHPExcel->getActiveSheet(0)->setCellValue('B' . ($i + 2), $data[$i]['password']);
$objPHPExcel->getActiveSheet(0)->setCellValue('C' . ($i + 2), $data[$i]['sex']);
}
$objPHPExcel->getActiveSheet()->setTitle('User');
$objPHPExcel->setActiveSheetIndex(0);
ob_end_clean(); //清除緩沖區,避免亂碼
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$name.'.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
}
}
這裡有兩部分,一部分read function,就是讀入Excel中,即將數據庫中內容導入到Excel,另一部分,push function,就是講Excel數據上傳到數據庫。
第三,創建一個ExcelAction.clsaa.php,在目錄E:\Workspace\PHP\thinkphp2\Home\Lib\Action下面,ExcelAction.clsaa.php源代碼如下:
1 <?php
2 class ExcelAction extends Action {
3 public function __construct()
4 {
5 import('ORG.Util.ExcelToArray');//導入excelToArray類
6 }
7
8 public function index()
9 {
10 $this->display();
11 }
12 public function add()
13 {
14 dump($_FILES);
15
16 $tmp_file = $_FILES ['file_stu'] ['tmp_name'];
17 $file_types = explode ( ".", $_FILES ['file_stu'] ['name'] );
18 $file_type = $file_types [count ( $file_types ) - 1];
19
20 /*判別是不是.xls文件,判別是不是excel文件*/
21 if (strtolower ( $file_type ) != "xlsx" && strtolower ( $file_type ) != "xls")
22 {
23 $this->error ( '不是Excel文件,重新上傳' );
24 }
25
26 /*設置上傳路徑*/
27 $savePath = 'E:\Workspace\PHP\thinkphp\Uploads\\';
28 /*以時間來命名上傳的文件*/
29 $str = date ( 'Ymdhis' );
30 $file_name = $str . "." . $file_type;
31
32 /*是否上傳成功*/
33 if (! copy ( $tmp_file, $savePath . $file_name ))
34 {
35 $this->error ( '上傳失敗' );
36 }
37 $ExcelToArray=new ExcelToArray();//實例化
38 $res=$ExcelToArray->read($savePath.$file_name,"UTF-8",$file_type);//傳參,判斷office2007還是office2003
39 foreach ( $res as $k => $v ) //循環excel表
40 {
//這一步判斷,是為了在Excel內第一行一定是行標題,這裡將第一行忽略,直接從第二行讀入數據,若沒有行標題,則不需要進行if判斷,且$k=$k-1;
41 if($k!=1){
42 $k=$k-2;//addAll方法要求數組必須有0索引
43 $data[$k]['username'] = $v[0];//創建二維數組
44 $data[$k]['password'] = $v[1];
45 $data[$k]['sex'] = $v [2];
46 }
47 }
48
49 //dump($data[0]);
50 $kucun=M('User');//M方法
51 $result=$kucun->addAll($data);
52 if(! $result)
53 {
54 $this->error('導入數據庫失敗');
55 exit();
56 }
57 else
58 {
59 $this->success ( '導入成功' );
60 }
61 }
62
63 public function load(){
64 $data= M('User')->select(); //查出數據
65 dump($data);
66 $name='Usertable'; //生成的Excel文件文件名
67 $ExcelToArray=new ExcelToArray();//實例化
68 $res=$ExcelToArray->push($data,$name);
69 }
70 }
第四,就是創建相應的模板,在目錄E:\Workspace\PHP\thinkphp2\Home\Tpl下,創建Excel文件夾,新建index.html文件,源代碼如下:
1 <form method="post" action="__APP__/Excel/add" enctype="multipart/form-data"> 2 <h3>導入Excel表:</h3><input type="file" name="file_stu" /> 3 4 <input type="submit" value="導入" /> 5 </form> 6 <form method="post" action="__APP__/Excel/load" enctype="multipart/form-data"> 7 <input type="submit" value="導出" /> 8 </form>
最後,只需要進行測試就可以了。
ps,數據庫信息如下:
例如:新建數據庫thinkphp,建立表user,user表信息如下:
id username password sex 1 zs 123 1以上就是使用PhpExcel的全部步驟,謝謝!