很多文章都有提到關(guān)于使用phpExcel實現(xiàn)Excel數(shù)據(jù)的導(dǎo)入導(dǎo)出,大部分文章都差不多,或者就是轉(zhuǎn)載的,都會出現(xiàn)一些問題,下面是本人研究phpExcel的使用例程總結(jié)出來的使用方法,接下來直接進入正題。
首先先說一下,本人的這段例程是使用在Thinkphp的開發(fā)框架上,要是使用在其他框架也是同樣的方法,很多人可能不能正確的實現(xiàn)Excel的導(dǎo)入導(dǎo)出,問題基本上都是phpExcel的核心類引用路徑出錯,如果有問題大家務(wù)必要對路勁是否引用正確進行測試。
(一)導(dǎo)入Excel
第一,在前臺html頁面進行上傳文件:如:
<form method="post" action="php文件" enctype="multipart/form-data">
<h3>導(dǎo)入Excel表:</h3><input type="file" name="file_stu" />
<input type="submit" value="導(dǎo)入" />
</form>
第二,在對應(yīng)的php文件進行文件的處理
if (! empty ( $_FILES ['file_stu'] ['name'] ))
{
$tmp_file = $_FILES ['file_stu'] ['tmp_name'];
$file_types = explode ( ".", $_FILES ['file_stu'] ['name'] );
$file_type = $file_types [count ( $file_types ) - 1];
/*判別是不是.xls文件,判別是不是excel文件*/
if (strtolower ( $file_type ) != "xls")
{
$this->error ( '不是Excel文件,重新上傳' );
}
/*設(shè)置上傳路徑*/
$savePath = SITE_PATH . '/public/upfile/Excel/';
/*以時間來命名上傳的文件*/
$str = date ( 'Ymdhis' );
$file_name = $str . "." . $file_type;
/*是否上傳成功*/
if (! copy ( $tmp_file, $savePath . $file_name ))
{
$this->error ( '上傳失敗' );
}
/*
*對上傳的Excel數(shù)據(jù)進行處理生成編程數(shù)據(jù),這個函數(shù)會在下面第三步的ExcelToArray類中
注意:這里調(diào)用執(zhí)行了第三步類里面的read函數(shù),把Excel轉(zhuǎn)化為數(shù)組并返回給$res,再進行數(shù)據(jù)庫寫入
*/
$res = Service ( 'ExcelToArray' )->read ( $savePath . $file_name );
/*
重要代碼 解決Thinkphp M、D方法不能調(diào)用的問題
如果在thinkphp中遇到M 、D方法失效時就加入下面一句代碼
*/
//spl_autoload_register ( array ('Think', 'autoload' ) );
/*對生成的數(shù)組進行數(shù)據(jù)庫的寫入*/
foreach ( $res as $k => $v )
{
if ($k != 0)
{
$data ['uid'] = $v [0];
$data ['password'] = sha1 ( '111111' );
$data ['email'] = $v [1];
$data ['uname'] = $v [3];
$data ['institute'] = $v [4];
$result = M ( 'user' )->add ( $data );
if (! $result)
{
$this->error ( '導(dǎo)入數(shù)據(jù)庫失敗' );
}
}
}
}
第三:ExcelToArrary類,用來引用phpExcel并處理Excel數(shù)據(jù)的
class ExcelToArrary extends Service{
public function __construct() {
/*導(dǎo)入phpExcel核心類 注意 :你的路徑跟我不一樣就不能直接復(fù)制*/
include_once('./Excel/PHPExcel.php');
}
/**
* 讀取excel $filename 路徑文件名 $encode 返回數(shù)據(jù)的編碼 默認為utf8
*以下基本都不要修改
*/
public function read($filename,$encode='utf-8'){
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$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;
}
}
第四,以上就是導(dǎo)入的全部內(nèi)容,phpExcel包附在最后。
(二)Excel的導(dǎo)出(相對于導(dǎo)入簡單多了)
第一,先查出數(shù)據(jù)庫里面要生成Excel的數(shù)據(jù),如:
$data= M('User')->findAll(); //查出數(shù)據(jù)
$name='Excelfile'; //生成的Excel文件文件名
$res=service('ExcelToArrary')->push($data,$name);
第二,ExcelToArrary類,用來引用phpExcel并處理數(shù)據(jù)的
class ExcelToArrary extends Service{
public function __construct() {
/*導(dǎo)入phpExcel核心類 注意 :你的路徑跟我不一樣就不能直接復(fù)制*/
include_once('./Excel/PHPExcel.php');
}
/* 導(dǎo)出excel函數(shù)*/
public function push($data,$name='Excel'){
error_reporting(E_ALL);
date_default_timezone_set('Europe/London');
$objPHPExcel = new PHPExcel();
/*以下是一些設(shè)置 ,什么作者 標題啊之類的*/
$objPHPExcel->getProperties()->setCreator("轉(zhuǎn)彎的陽光")
->setLastModifiedBy("轉(zhuǎn)彎的陽光")
->setTitle("數(shù)據(jù)EXCEL導(dǎo)出")
->setSubject("數(shù)據(jù)EXCEL導(dǎo)出")
->setDescription("備份數(shù)據(jù)")
->setKeywords("excel")
->setCategory("result file");
/*以下就是對處理Excel里的數(shù)據(jù), 橫著取數(shù)據(jù),主要是這一步,其他基本都不要改*/
foreach($data as $k => $v){
$num=$k+1;
$objPHPExcel->setActiveSheetIndex(0)
//Excel的第A列,uid是你查出數(shù)組的鍵值,下面以此類推
->setCellValue('A'.$num, $v['uid'])
->setCellValue('B'.$num, $v['email'])
->setCellValue('C'.$num, $v['password'])
}
$objPHPExcel->getActiveSheet()->setTitle('User');
$objPHPExcel->setActiveSheetIndex(0);
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;
}
第三,以上就是導(dǎo)出的全部內(nèi)容,phpExcel包附在最后。