1.上傳新增excel
(需下載PHPExcel類檔案,引入到專案類庫裡)
//接收前臺檔案,
public function addExcel()
{
//接收前臺檔案
$ex = $_FILES[`excel`];
//重設定檔名
$filename = time().substr($ex[`name`],stripos($ex[`name`],`.`));
$path = `./excel/`.$filename;//設定移動路徑
move_uploaded_file($ex[`tmp_name`],$path);
//表用函式方法 返回陣列
$exfn = $this->_readExcel($path);
$this->redirect(`input`);
}
//建立一個讀取excel資料,可用於入庫
public function _readExcel($path)
{
//引用PHPexcel 類
include_once(IWEB_PATH.`core/util/PHPExcel.php`);
include_once(IWEB_PATH.`core/util/PHPExcel/IOFactory.php`);//靜態類
$type = `Excel2007`;//設定為Excel5代表支援2003或以下版本,Excel2007代表2007版
$xlsReader = PHPExcel_IOFactory::createReader($type);
$xlsReader->setReadDataOnly(true);
$xlsReader->setLoadSheetsOnly(true);
$Sheets = $xlsReader->load($path);
//開始讀取上傳到伺服器中的Excel檔案,返回一個二維陣列
$dataArray = $Sheets->getSheet(0)->toArray();
return $dataArray;
}
2,匯出下載Excel檔案
<span style="font-size:24px;">/**
* 匯出檔案
* @author Jef
* @param
* @return
*/</span>
public function export_file()
{
$u = new IQuery(`user`);
$data = $u->find();
$name = `user_`.time();
$this->push($data,$name);
$this->redirect(`export`);
}
/* 匯出excel函式*/
public function push($data,$name=`Excel`)
{
include_once(IWEB_PATH.`core/util/PHPExcel.php`);
error_reporting(E_ALL);
date_default_timezone_set(`Europe/London`);
$objPHPExcel = new PHPExcel();
/*以下是一些設定 ,什麼作者 標題啊之類的*/
$objPHPExcel->getProperties()->setCreator("轉彎的陽光")
->setLastModifiedBy("轉彎的陽光")
->setTitle("資料EXCEL匯出")
->setSubject("資料EXCEL匯出")
->setDescription("備份資料")
->setKeywords("excel")
->setCategory("result file");
/*以下就是對處理Excel裡的資料, 橫著取資料,主要是這一步,其他基本都不要改*/
foreach($data as $k => $v){
$num=$k+1;
$objPHPExcel->setActiveSheetIndex(0)//Excel的第A列,uid是你查出陣列的鍵值,下面以此類推
->setCellValue(`A`.$num, $v[`id`])
->setCellValue(`B`.$num, $v[`username`])
->setCellValue(`C`.$num, $v[`password`])
->setCellValue(`D`.$num, $v[`email`])
->setCellValue(`E`.$num, $v[`head_ico`])
->setCellValue(`F`.$num, $v[`invite`])
->setCellValue(`G`.$num, $v[`is_seller_invite`]);
}
$objPHPExcel->getActiveSheet()->setTitle(`User`);
$objPHPExcel->setActiveSheetIndex(0);
header(`Content-Type: applicationnd.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;
}